簡體   English   中英

如何檢測指定 x,y 位置的白色像素

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

我有一張圖像,我在 OpenCV 中使用給定的 x,y 坐標進行遮罩和裁剪。 我還嘗試檢測並顯示所述圖像中的白色像素,由於我在另一篇 Stackoverflow 帖子中得到的答案的幫助,現在工作正常。

我目前有以下內容:

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:

輸出

理想情況下,我現在想做的是嘗試查看位置(對象周圍的 20x20 正方形)中是否有白色像素,然后打印出一些東西。 我將如何 go 進行此操作。

我是否必須根據我得到的裁剪再次手動 select x,y 坐標,然后檢測白色像素,如果可以,是否可以同時使用兩個不同的坐標進行,或者是否有更簡單的方法?

您可以對正方形內的像素值求和,如果該數字高於某個閾值,則存在非黑色像素。 如果您絕對確定背景是死黑的,那么您可以檢查像素值總和是否為非零,以斷言您正在評估的區域中存在白色像素。

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

或使用 numpy:

np.sum(crop)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM