简体   繁体   English

cv2.imread:从固定位置读取任何图像文件

[英]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. 如何从固定位置或USB驱动器读取图像“ * .jpg”,而不管其名称如何。 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. 我正在研究一个从USB驱动器读取图像文件的项目,因此图像路径是已知的,并且该驱动器将只有一个.jpg文件,但是鉴于文件名可以使用cv2.imread()进行读取更改。

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). 这个问题还不清楚,但是我假设您有一个固定的路径(您知道USB设备的字母),并且其中只有一个jpg文件(否则我必须说如何选择)。 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? 这意味着要列出一个文件夹中的所有jpg文件,然后选择第一个(或所需的)元素,您可以使用模块os.path进行此操作,请参见Python:如何找到所有具有特定扩展名的文件?

This code is based on @Vincenzooo answer, and works for me: 这段代码基于@Vincenzooo答案,对我有用:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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