I have the following code and it works very well for me, what it does is simple.
In essence it is to verify that there is a camera connected, if it works true
just capture a photo and save it as photo.png , if it is it false
shows an error message, so far so good, now what I need to do with the photo I just took is remove the background.
It should be noted that the background will always be white, I use linux, but I think it is irrelevant.
import cv2
import numpy as np
from matplotlib import pyplot as plt
"""
En este caso, 0 quiere decir que queremos acceder
a la cámara 0. Si hay más cámaras, puedes ir probando
con 1, 2, 3...
"""
cap = cv2.VideoCapture(0)
read, frame = cap.read()
if read == True:
cv2.imwrite("foto.png", frame)
print("Foto tomada correctamente")
else:
print("Error al acceder a la cámara")
#Finalmente liberamos o soltamos la cámara
cap.release()
I have improved my code considerably
in addition to removing the background and painting it completely white
I have put a
for
to take the number of photos you want, in this case it would be changed in the rangefor acum in range(40):
and immediately organize the completely white background or the color that I want in the Parameter part, it will save the photos in a folder that I defined img.
MASK_COLOR = (1.0,1.0,1.0) # In BGR format
I attach the code in case someone else needs it in a project.
Post I relied on
I bring you the answer from http://benjamintan.io/blog/2018/05/24/making-transparent-backgrounds-with-numpy-and-opencv-in-python/
To your code you must add:
to add the alpha channel to the image (pay attention to the color order: BGR and not RGB), and
to find the pixels that are white , i.e. (255, 255, 255) in BGR. On the same line you replace the colors.
To change pixels that are not completely white, you can change the line above to
where the value of atol (
atol=200
) indicates how close the value is, with 200 being a fairly high value.I leave you the complete code: