繁体   English   中英

opencv用白色替换视频中的所有黑色像素

[英]opencv replace all black colored pixels in video with white

我们如何将视频中的所有黑色替换为白色。

我尝试了这个但是它不起作用

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转换为灰度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM