[英]Python If Value of pixel in an image is then print
我有一個小圖像,我想找到所有相同的 RGB 值,然后將其與我的變量進行比較,如果匹配打印匹配或類似。
下面是我從其他來源整理的一小段。
我可以打印我找到的顏色,但每次在圖像中找到該值時它都會打印一行。
有沒有更好的方法來搜索圖像並將其與單個 RGB 值匹配? 然后如果發現做一件事。
import cv2
path = '3.png'
blue = int(224)
green = int(96)
red = int(32)
img = cv2.imread(path)
x,y,z = img.shape
for i in range(x):
for j in range(y):
if img[i,j,0]==blue & img[i,j,1]==green & img[i,j,1]==red:
print("Found colour at ",i,j)
一般 Python 建議:不要說blue = int(224)
。 就說blue = 224
您的程序希望找到這些確切的值。 在任何類型的照片中,沒有什么是准確的。 您需要找到值的范圍。
cv.imread
按 BGR 順序返回數據。 請注意,如果您訪問 numpy 數組中的單個值。
用這個:
import numpy as np
import cv2 as cv
img = cv.imread("3.png")
lower_bound = (224-20, 96-20, 32-20) # BGR
upper_bound = (224+20, 96+20, 32+20) # BGR
mask = cv.inRange(img, lower_bound, upper_bound)
count = cv.countNonZero(mask)
print(f"picture contains {count} pixels of that color")
如果您需要知道該顏色的像素在哪里,請解釋您需要它的用途。 這些點的列表通常是無用的。 有更多有用的方法可以獲取這些位置,但它們取決於您需要這些信息的原因和用途。
我認為這可能會對您有所幫助:)
import cv2
import numpy as np
r = int(255)
g = int(255)
b = int(255)
img = 255*np.ones((5,5,3), np.uint8)
[rows, cols] = img.shape[:2]
print(img.shape[:2])
print(img.shape)
for i in range(rows):
for j in range(cols):
if img[i, j][0] == r and img[i, j][1] == g and img[i, j][2] == b:
print(img[i, j])
print(i, j)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.