假设您的图像表示为numpy形状数组(height, width, channels)(cv2.imread返回的内容),您可以执行以下操作:
height, width, _ = img.shape
for i in range(height):
for j in range(width):
# img[i, j] is the RGB pixel at position (i, j)
# check if it's [0, 0, 0] and replace with [255, 255, 255] if so
if img[i, j].sum() == 0:
img[i, j] = [255, 255, 255]
Run Code Online (Sandbox Code Playgroud)
更快的、基于掩码的方法如下所示:
# get (i, j) positions of all RGB pixels that are black (i.e. [0, 0, 0])
black_pixels = np.where(
(img[:, :, 0] == 0) &
(img[:, :, 1] == 0) &
(img[:, :, 2] == 0)
)
# set those pixels to white
img[black_pixels] = [255, 255, 255]
Run Code Online (Sandbox Code Playgroud)