无法转换在列表图像数据中存储图像的Python

2024-05-17 14:03:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图存储在一个列表中的每一个jpg图像。我有1000多张照片。在将图像存储到列表中之前,我可以显示它。但是,一旦它在我的列表中,我就不能显示它。似乎图像在进入列表之前就已经关闭了,即使我在列表中存储图像之后关闭了它。请帮忙。你知道吗

image_list = []   # list for train images
filename = 'data/training_images/'  # file that has train images
for filename in glob.glob('data/training_images/*.jpg'):  # grab all the images
    im=Image.open(filename)
    # plt.imshow(im)   --> works
    image_list.append(im) 
    # plt.imshow(image_list[0])   --> works
    im.close()  # I need it because I have many images
    plt.imshow(image_list[0])  # --> error; does not work

TypeError: Image data cannot be converted to float


Tags: 图像image列表fordatatrainingtrainplt
2条回答

从Image.open打开()

This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data

此函数返回图像对象。一旦你打电话给即时消息关闭(),它关闭文件指针,因此无法访问图像。你知道吗

我们可以使用cv2或matplotlib读取图像并将其存储在列表中。你知道吗

 im = cv2.imread(filename) 
 # im will be a numpy array 
 image_list.append(im) 

放入列表的数据是open函数的结果。该函数返回的值不是文件的内容,而是文件句柄。在CPython中,我相信句柄只是一个整数。这个句柄告诉Python和操作系统在哪里找到文件,只要文件保持打开状态。关闭文件时,句柄将变得毫无意义。你知道吗

打开文件后,需要将每个文件的内容转换为Python数据类型,并将内容存储到列表中。也许可以使用read函数将数据放入bytes结构中。你知道吗

相关问题 更多 >