Automatically detecting Image and Video Files for further processing

混江龙づ霸主 提交于 2019-12-24 17:25:44

问题


So I want to write a script which I only give a path to either a folder or a file, and it will then detect all video and image files and put them in a list of videos and a list of images. For each video I'll edit the frames and produce an output video. Then I'll do the same with all images. But what is the best way to determine whether a file is a valid image or video? Or do I have to do something like this:

# if os.path.isdir(path_to_folder)
video_list = []
image_list = []
for file in os.listdir(path_to_folder):
  try:
    cv2.VideoCapture(file)
    video_list.append(file)
    continue
  except:
    pass

  try:
    cv2.imread(file)
    image_list.append(file)
    continue
  except:
    pass

I really hope there's a better way to do this. I didn't even test this code, it's so sloppy I'd prefer not to have to resort to this method.


回答1:


There is a library available just for this purpose. It surely will simplify the task.

Install the library filetype from HERE which can be easily installed using pip. The list of supported file types are also mentioned.

import filetype
file = filetype.guess(r'C:\Users\Jackson\Desktop\car.png')
if file is None:
    print('Cannot guess file type!')

elif:
    print('File extension: %s' % file.extension)
    print('File MIME type: %s' % file.mime)

I passed in a .png file which resulted in:

File extension: png
File MIME type: image/png

Using the mime attribute you can determine what type your file is.



来源:https://stackoverflow.com/questions/51439435/automatically-detecting-image-and-video-files-for-further-processing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!