In this tutorial, you will learn how to use OpenCV Python’s library for cartooning a webcam stream. While this is a relatively simple coding example, will require a strong CPU to maintain good performance, especially single-thread performance. A processor like Core i5 9600k or Ryzen 5 5600X and higher is recommended. Keep in mind that a webcam stream is nothing more than a series for images refreshed at 25-30 frames per second, so essentially we will manipulate an image in a while loop, that is being refreshed 25-30 frames per second.
Cartooning A Video Stream
- Create a VideoCapture object and read it from the input file.
- Check if the camera opened successfully.
- Read the video stream.
- Release the video capture object.
- Close all the frames.
Cartooning Webcam Python Code
import cv2 # Create a VideoCapture object and read from input file # If the input is the camera, pass 0 instead of the video file name webcam = cv2.VideoCapture(0, cv2.CAP_DSHOW) # Check if camera opened successfully if (webcam.isOpened() == False): print("Error opening video stream or file") # Read the video while(webcam.isOpened()): # Capture frame-by-frame ret, frame = webcam.read() if ret == True: color = cv2.bilateralFilter(frame, 9, 9, 7) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) blur = cv2.medianBlur(gray, 7) edges = cv2.adaptiveThreshold(blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2) frame_edge = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) cartoon = cv2.bitwise_and(color, frame_edge) # Display the resulting frame cv2.imshow('Cartoonized', cartoon) # Press q on keyboard to exit if cv2.waitKey(25) == ord('q'): break # Press s on keyboard to save a screenshot elif cv2.waitKey(25) == ord('s'): cv2.imwrite('screenshot.png', cartoon) # When everything done, release the video capture object webcam.release() # Closes all the frames cv2.destroyAllWindows()
Cartooning An Image
When we want to use an image as an input, things are getting much simpler and straightforward. In this case, there is no need to run any loops, but only to process the input image apply the exact same process as we did with the webcam stream above.
Cartooning Image Python Code
import cv2 image = cv2.imread('input-image.jpg') color = cv2.bilateralFilter(image, 9, 9, 7) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.medianBlur(gray, 7) edges = cv2.adaptiveThreshold( blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 2) frame_edge = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB) cartoon = cv2.bitwise_and(color, frame_edge) # Display the resulting image cv2.imshow('Cartoonized', cartoon) # Save the cartoonized image cv2.imwrite('screenshot.png', cartoon) cv2.waitKey(0) # "0" is Used to close the image window cv2.destroyAllWindows()
That was all for this tutorial, hope you found the code helpfull!