如何使用库函数将所有白色(255,255,255)像素转换为黑色(0,0,0)?

How to convert all white(255,255,255) pixels to black (0,0,0) using a library function?

我不想按像素转换它,因为它很复杂。有没有库函数可以一次性把所有的白色像素转换成黑色,而不影响其他像素?

import numpy as np
import cv2
img1 = cv2.imread('background.jpg')

基于 OpenCV 论坛:Replace a range of colors with a specific color in python

img[np.where((img==[255,255,255]).all(axis=2))] = [0,0,0]

工作示例:

import cv2
import numpy as np
import time

cv2.namedWindow('window')

img = cv2.imread('image.jpg')

start = time.time()

img[np.where((img==[255,255,255]).all(axis=2))] = [0,0,0]

end = time.time()
print('time:', end-start)

cv2.imshow('window', img)

cv2.waitKey()
cv2.destroyAllWindows()

对于图像 512x341 时间是 0.011182308197021484(秒)


编辑: 前面的例子 numpyfor-loops

快得多
import cv2
import numpy as np
import time

cv2.namedWindow('window')

img = cv2.imread('Obrazy/images/image.jpg')

y, x, z = img.shape # `y` is first in `shape`
print(x, y)

start = time.time()

for row in range(y):
    for col in range(x):
        if all(img[row,col] == [255,255,255]):
            img[row,col] = [0,0,0]
end = time.time()

print('time:', end-start)

cv2.imshow('window', img)

cv2.waitKey()
cv2.destroyAllWindows()

对于图像512x341,时间是1.5046415328979492(秒)


    if (img[row,col] == [255,255,255]).all():

时间是 2.443787097930908(秒)