【发布时间】:2020-07-12 16:23:46
【问题描述】:
我有一个.png 文件,我想扫描图像以检查其中是否有某个 RGB 值。例如,假设我有一张图像,并且想要检查 RGB 值 (255, 0, 0) 是否在图像中的某个位置。我将如何在 Python 中执行此操作?谢谢!
【问题讨论】:
标签: python python-3.x image colors png
我有一个.png 文件,我想扫描图像以检查其中是否有某个 RGB 值。例如,假设我有一张图像,并且想要检查 RGB 值 (255, 0, 0) 是否在图像中的某个位置。我将如何在 Python 中执行此操作?谢谢!
【问题讨论】:
标签: python python-3.x image colors png
我建议你使用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
【讨论】:
torch?此外,考虑到语法,answer = list(zip(*ind)) 是首选。
您可以使用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()
摘自我的回答here。
【讨论】:
np.tile 将像素扩展到所有值,np.sum 将 RGB 值折叠到一个通道(绝对差意味着零只是零的总和),np.argwhere 在值为零的情况下给出位置.
我有 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())
test == (255, 0, 0) 检查是否有任何颜色通道等于元组(255, 0, 0) 的相应条目。如果所有这 3 个条目评估为真,则相应位设置为 True。如果结果数组test.shape[0:2] 中的任何位为真,那么这就是结果。
【讨论】: