简体   繁体   English

如何检测指定 x,y 位置的白色像素

[英]How to detect white pixels in a specified x,y location

I have an image that I mask and crop in OpenCV with the given x,y coordinates.我有一张图像,我在 OpenCV 中使用给定的 x,y 坐标进行遮罩和裁剪。 I also tried to detect and show the white pixels in said image which works fine now thanks to the help of an answer I got in another Stackoverflow post.我还尝试检测并显示所述图像中的白色像素,由于我在另一篇 Stackoverflow 帖子中得到的答案的帮助,现在工作正常。

I currently have the following:我目前有以下内容:

import numpy as np
import cv2

img = cv2.imread('Image.jpg')
#img = cv2.imread('Image2.jpg') 
#img = cv2.imread('Image3.jpg')

mask = np.zeros(img.shape[:2], np.uint8)

bgdModel = np.zeros((1, 65), np.float64)
fgdModel = np.zeros((1, 65), np.float64)

rect = (1512, 20, 180, 185) # boundary of interest
cv2.grabCut(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img = img * mask2[:, :, np.newaxis]
cv2.imwrite('Image_mask.jpg', img)

# x,y coordinates for specified "fixed" location
mx = (1510, 22, 110, 185)
x, y, h, w = mx

# Output to files
crop = img[y:y+h, x:x+w]
cv2.imwrite('Image_crop.jpg', crop)

cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.imwrite('Image_cont.jpg', img)

# Detect white pixels from cropped image
img = cv2.imread('Image_crop.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret,gray = cv2.threshold(gray, 150,255,0)
gray2 = gray.copy()

cv2.imshow('IMG',gray2)

cv2.waitKey(0)
cv2.destroyAllWindows()

Output: Output:

输出

Ideally what I want to do now is try and see if the location(20x20 square around object) has white pixels in it and then print something out.理想情况下,我现在想做的是尝试查看位置(对象周围的 20x20 正方形)中是否有白色像素,然后打印出一些东西。 How would I go about into doing this.我将如何 go 进行此操作。

Would I have to manually select x,y coordinates again based off the crop I got and then detect the white pixels and if so is it possible to do it simultaneously with two different coordinates or is there a more simpler approach?我是否必须根据我得到的裁剪再次手动 select x,y 坐标,然后检测白色像素,如果可以,是否可以同时使用两个不同的坐标进行,或者是否有更简单的方法?

You could sum the values of the pixels inside the square and if the number is above a certain threshold, there are non-black pixels.您可以对正方形内的像素值求和,如果该数字高于某个阈值,则存在非黑色像素。 If you are absolutely sure the background is dead black, then you can check that the pixel value sum is non-zero to assert there are white pixels in the are you are evaluating.如果您绝对确定背景是死黑的,那么您可以检查像素值总和是否为非零,以断言您正在评估的区域中存在白色像素。

crop = img[y:y+h, x:x+w]
if crop.sum() > 0:
    print("White pixels detected")

or using numpy:或使用 numpy:

np.sum(crop)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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