Reputation: 673
How can we replace all the black color from a video to white.
I tried this but its not working
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]
Upvotes: 0
Views: 2397
Reputation: 4552
The following code snippet shows how to replace all black pixels in a BGR image with white using only Numpy. You can apply it to each frame of your video.
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.
Please note that this will only replace true black pixels. In a real-world video, you'd do some thresholding as a pre-processing step as it is very rare to have perfectly black pixels.
EDIT:
To affect dark pixels under a certain value but not necessarily completely black, use thresholding:
# 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.
This only works for grayscale images but maybe you should consider converting your image from BGR to grayscale in any case if your goal is to detect black pixels to turn them into white.
Upvotes: 1