我有一个.png
文件,我想扫描图像,检查其中是否有某个RGB值。例如,假设我有一张图像,想检查RGB值(255, 0, 0)
是否在图像中。在Python中我该如何做到这一点?谢谢
我建议您使用PIL Getpixel或PIL Getdata
from PIL import Image
im = Image.open('whatever.png').convert("RGB")
# get pixels
pixels = [im.getpixel((i, j)) for j in range(im.height) for i in range(im.width)]
# or
pixels = [i for i in im.getdata()]
#check if tuple of pixel value exists in array-pixel
print((255, 0, 0) in pixels) #True if exists, False if it doesn't
这应该有效。。
import cv2
import numpy as np
img = cv2.imread(r'circle.png')
ind = np.where((img[:, :, 0]==255) & (img[:, :, 1]==0) & (img[:, :, 2]==0))
answer = list(zip(ind[0], ind[1]))
print(answer) # Prints row and column indices in tuples
您可以使用cv2
包加载图像,并使用numpy
将其搜索为数组:
import cv2
import numpy as np
img = cv2.imread('one.png')
pixel = img[801,600]
print (pixel) # pixel value i am searching for
def search_array():
pixel_tile = np.tile(pixel, (*img.shape[:2], 1))
diff = np.sum(np.abs(img - pixel_tile), axis=2)
print("n".join([f"SUCCESS - {idx}" for idx in np.argwhere(diff == 0)]))
if __name__ == "__main__":
search_array()
取自我在这里的回答。
我有一个替代numpy的解决方案。
import cv2
import numpy as np
im = cv2.imread('your_image.png')
print('Your color is in the image', (im == (255, 0, 0)).all(axis=-1).max())
CCD_ 5检查颜色通道中的任何一个是否等于元组CCD_。如果所有这3个条目的值都为真,则相应的位被设置为True
。如果得到的形状为test.shape[0:2]
的阵列中的任何位为真,则这将是结果。