简体   繁体   English

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

[英]Python If Value of pixel in an image is then print

I have a small image that I would like to find all RGB values that are the same and then compare that against my variable and if the match print match or similar.我有一个小图像,我想找到所有相同的 RGB 值,然后将其与我的变量进行比较,如果匹配打印匹配或类似。

Below is a little snippet that I have put together from other sources.下面是我从其他来源整理的一小段。

I am able to print that I found the colour but it will print a line for every time that value is found in the image.我可以打印我找到的颜色,但每次在图像中找到该值时它都会打印一行。

Is there a better way to search an image and match that to a single RGB value?有没有更好的方法来搜索图像并将其与单个 RGB 值匹配? Then if found do a thing.然后如果发现做一件事。

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)

General Python advice: do not say blue = int(224) .一般 Python 建议:不要blue = int(224) Just say blue = 224就说blue = 224

Your program expects to find those exact values.您的程序希望找到这些确切的值。 In any kind of photo, nothing is exact.在任何类型的照片中,没有什么是准确的。 You need to find ranges of values.您需要找到值的范围

cv.imread returns data in BGR order. cv.imread按 BGR 顺序返回数据。 Be aware of that if you access individual values in the numpy array.请注意,如果您访问 numpy 数组中的单个值。

Use this:用这个:

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")

And if you need to know where pixels of that color are, please explain what you need that for.如果您需要知道该颜色的像素在哪里,请解释您需要它的用途。 A list of those points is generally useless.这些点的列表通常是无用的。 There are more useful ways to get these locations but they depend on why you need this information, what for.有更多有用的方法可以获取这些位置,但它们取决于您需要这些信息的原因和用途。

I think this may help you with small touching:)我认为这可能会对您有所帮助:)

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