gray_next_to_black = gray_mask & shifted_black_mask
# gray_next_to_black_idx = np.where(gray_next_to_black) # Get the indices if required
代码示例:
import cv2
import numpy as np
# Sample image for testing:
img = np.array([[[0, 100, 0], [0, 100, 0], [0, 100, 0], [0, 0, 0]],
[[0, 100, 0], [80, 80, 80], [80, 80, 80], [0, 0, 0]],
[[0, 100, 0], [80, 80, 80], [80, 80, 80], [0, 100, 0]],
[[0, 100, 0], [80, 80, 80], [0, 0, 0], [0, 100, 0]]], np.uint8)
gray_mask = np.all(np.abs(img - (80, 71, 71)) < 10, axis=-1) # Create a mask with True where pixel is gray and False otherwise.
black_mask = np.all(img == 0, axis=-1) # Create a mask with True where pixel is black and False otherwise.
# Shift the black mask one column to the left
shifted_black_mask = np.pad(black_mask[:, 1:], ((0, 0), (0, 1)), 'constant') # Crop from the second column to the end, and add column of zeros at the right hand side.
# Apply and operation between the gray mask and the shifted black mask
# The result is True where gray pixel has a black pixel from it's right
gray_next_to_black = gray_mask & shifted_black_mask
# Get the indices if required:
# gray_next_to_black_idx = np.where(gray_next_to_black)
# Show image and masks for testing:
cv2.imshow("img", cv2.resize(img, (256, 256), interpolation=cv2.INTER_NEAREST))
cv2.imshow("gray_mask", cv2.resize(gray_mask.astype(np.uint8)*255, (256, 256), interpolation=cv2.INTER_NEAREST))
cv2.imshow("black_mask", cv2.resize(black_mask.astype(np.uint8)*255, (256, 256), interpolation=cv2.INTER_NEAREST))
cv2.imshow("shifted_black_mask", cv2.resize(shifted_black_mask.astype(np.uint8)*255, (256, 256), interpolation=cv2.INTER_NEAREST))
cv2.imshow("gray_next_to_black", cv2.resize(gray_next_to_black.astype(np.uint8)*255, (256, 256), interpolation=cv2.INTER_NEAREST))
cv2.waitKey()
cv2.destroyAllWindows()
1条答案
按热度按时间n3ipq98p1#
为了找到紧邻黑色像素左侧的灰色像素,我们可以应用以下阶段:
True
创建一个遮罩,其中像素为灰色,否则为False
。与上面的代码相同,但没有
np.where
:True
创建一个遮罩,其中像素为黑色,否则为False
。此阶段用于将黑色像素放置在我们希望找到的灰色像素的位置。
我们在蒙版的右侧大小添加一列
False
值(用于在裁剪后“校正”蒙版大小)。代码示例:
img
:gray_mask
:black_mask
:shifted_black_mask
:gray_next_to_black
: