我们如何将视频中的所有黑色替换为白色。
我尝试了这个,但是没有用
import cv2
import numpy as np
from matplotlib import pyplot as plt
cap = cv2.VideoCapture(0)
while(1):
ret, img = cap.read()
#Remove all black color and replace it with white
img[np.where((img == [0,0,0]).all(axis = 2))] = [255,255,255]
最佳答案
以下代码段显示了如何仅使用Numpy将BGR图像中的所有黑色像素替换为白色。您可以将其应用于视频的每个帧。
import numpy as np
a = np.zeros((100,100, 3), dtype= np.uint8) # Original image. Here we use a black image but you can replace it with your video frame.
white = np.full((100, 100, 3), 255, dtype=np.uint8) # White image
a = np.where(a[:,:] == [0,0,0], white, a) # This is where we replace black pixels.
请注意,这只会替换纯黑色像素。在现实世界的视频中,您需要做一些阈值处理作为预处理步骤,因为很少有完美的黑色像素。
编辑:
要在一定值下(但不一定是全黑)影响暗像素,请使用阈值设置:
# We make all pixels with value lower than 100 into black pixels.
# This only works with grayscale images.
a = cv2.cvtColor(a, cv.COLOR_BGR2GRAY) # Convert image to grayscale
ret, a = cv2.threshold(a, 100, 255, cv2.THRESH_TOZERO) # Make gray pixels under 100 black.
这仅适用于灰度图像,但是如果您的目标是检测黑色像素以将其变为白色,则无论如何都应考虑将图像从BGR转换为灰度。
关于python - opencv用白色替换视频中的所有黑色像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50850692/