ofi*_*ubi 6 python numpy image image-processing
我试图使用NumPy获取与特定颜色不同的图像像素列表.
例如,在处理以下图像时:
我设法使用以下方法获取所有黑色像素的列表:
np.where(np.all(mask == [0,0,0], axis=-1))
Run Code Online (Sandbox Code Playgroud)
但是当我尝试做的时候:
np.where(np.all(mask != [0,0,0], axis=-1))
Run Code Online (Sandbox Code Playgroud)
我得到一个非常奇怪的结果:
看起来NumPy只返回了指数,R,G和B都是非0
这是我正在尝试做的最小例子:
import numpy as np
import cv2
# Read mask
mask = cv2.imread("path/to/img")
excluded_color = [0,0,0]
# Try to get indices of pixel with different colors
indices_list = np.where(np.all(mask != excluded_color, axis=-1))
# For some reason, the list doesn't contain all different colors
print("excluded indices are", indices_list)
# Visualization
mask[indices_list] = [255,255,255]
cv2.imshow(mask)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
您应该使用np.any而不是np.all第二种情况选择除黑色像素以外的所有像素:
np.any(image != [0, 0, 0], axis=-1)
Run Code Online (Sandbox Code Playgroud)
或者通过以下方式反转布尔数组来获得黑色像素的补充~:
black_pixels_mask = np.all(image == [0, 0, 0], axis=-1)
non_black_pixels_mask = ~black_pixels_mask
Run Code Online (Sandbox Code Playgroud)
工作范例:
import numpy as np
import matplotlib.pyplot as plt
image = plt.imread('example.png')
plt.imshow(image)
plt.show()
Run Code Online (Sandbox Code Playgroud)
image_copy = image.copy()
black_pixels_mask = np.all(image == [0, 0, 0], axis=-1)
non_black_pixels_mask = np.any(image != [0, 0, 0], axis=-1)
# or non_black_pixels_mask = ~black_pixels_mask
image_copy[black_pixels_mask] = [255, 255, 255]
image_copy[non_black_pixels_mask] = [0, 0, 0]
plt.imshow(image_copy)
plt.show()
Run Code Online (Sandbox Code Playgroud)
如果有人使用matplotlib绘制结果并获得完全黑色的图像或警告,请参阅此文章:将所有非黑色像素转换为一种颜色不会产生预期的输出