不能使用图像类型的集合?
Can't use sets with Image types?
我正在使用 pyautogui
库,我想将我的屏幕截图保存在一个没有重复的列表中。该类型是 Image
格式,这使得它不可散列。有什么办法可以解决这个问题,让我可以使用图片集吗?
我收到的错误消息是 TypeError: unhashable type: 'Image'
。
import pyautogui
import time
import cv2
import numpy as np
import os
x = 1
pictures = []
check = []
while True:
image = pyautogui.screenshot("image" + str(x) + '.png')
check.append(image)
print(len(check) != len(set(check)))
x+=1
time.sleep(2)
您可以使用 hashlib
模块为图像创建哈希值,然后手动将每个图像添加到集合中。我没有安装 pyautogui
,所以使用了 PIL
模块,它也提供了获取屏幕截图的功能。
import hashlib
#import pyautogui
from PIL import ImageGrab
import time
x = 1
pictures = []
image_hashes = set() # Empty set.
for i in range(10): # Do a limited number for testing.
# image = pyautogui.screenshot()
image = ImageGrab.grab()
# Compute an image hash value.
h = hashlib.sha256()
h.update(image.tobytes())
image_hash = h.digest()
if image_hash not in image_hashes:
pictures.append(image)
image_hashes.add(image_hash)
# image.save("image" + str(x) + '.png') # Save image file.
x += 1
time.sleep(2)
print(len(pictures), 'unique images obtained')
我正在使用 pyautogui
库,我想将我的屏幕截图保存在一个没有重复的列表中。该类型是 Image
格式,这使得它不可散列。有什么办法可以解决这个问题,让我可以使用图片集吗?
我收到的错误消息是 TypeError: unhashable type: 'Image'
。
import pyautogui
import time
import cv2
import numpy as np
import os
x = 1
pictures = []
check = []
while True:
image = pyautogui.screenshot("image" + str(x) + '.png')
check.append(image)
print(len(check) != len(set(check)))
x+=1
time.sleep(2)
您可以使用 hashlib
模块为图像创建哈希值,然后手动将每个图像添加到集合中。我没有安装 pyautogui
,所以使用了 PIL
模块,它也提供了获取屏幕截图的功能。
import hashlib
#import pyautogui
from PIL import ImageGrab
import time
x = 1
pictures = []
image_hashes = set() # Empty set.
for i in range(10): # Do a limited number for testing.
# image = pyautogui.screenshot()
image = ImageGrab.grab()
# Compute an image hash value.
h = hashlib.sha256()
h.update(image.tobytes())
image_hash = h.digest()
if image_hash not in image_hashes:
pictures.append(image)
image_hashes.add(image_hash)
# image.save("image" + str(x) + '.png') # Save image file.
x += 1
time.sleep(2)
print(len(pictures), 'unique images obtained')