Home > OS >  How to detect white pixels in a specified x,y location
How to detect white pixels in a specified x,y location

Time:10-05

I have an image that I mask and crop in OpenCV with the given x,y coordinates. 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.

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. How would I go about into doing this.

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?

CodePudding user response:

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:

np.sum(crop)
  • Related