繁体   English   中英

Python 如果图像中的像素值是然后打印

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM