简体   繁体   中英

cv2.imread: read any image file from a a fixed location

How to read an image '*.jpg' from a fixed location or USB drive regardless of its name. The path for the file will be the same but name of the file can change. I'm working on a project that reads an image file from the usb drive, so the image path is known and that drive will have just one .jpg file but how to read it using cv2.imread() given that the file name can change.

The question is a bit unclear, but I assume you have a fixed path (you know the letter of the USB device) and only one jpg file in it (otherwise I have to say how to chose). This means to list all jpg files in one folder and select the first (or the desired) element and you can do this using the module os.path , see Python: How can I find all files with a particular extension?

This code is based on @Vincenzooo answer, and works for me:

import os 
import cv2
def listFiles(path, extension):  
    return [f for f in os.listdir(path) if f.endswith(extension)]  
image = listFiles('G:/Images','.jpg')  

img = cv2.imread(image[0],0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM