|
| 1 | +importcv2,argparse,sys |
| 2 | + |
| 3 | + |
| 4 | +# In this function, we accept an image and convert it to a cartoon form. |
| 5 | +defcartoonizer(image_name): |
| 6 | +# Load the image to cartoonize. |
| 7 | +image_to_animate=cv2.imread(image_name) |
| 8 | + |
| 9 | +# Apply a bilateral filter to smoothen the image while preserving edges. |
| 10 | +smoothened_image=cv2.bilateralFilter(image_to_animate,d=9,sigmaColor=75,sigmaSpace=75) |
| 11 | + |
| 12 | +# Convert image to gray and create an edge mask using adaptive thresholding. |
| 13 | +gray_image=cv2.cvtColor(smoothened_image,cv2.COLOR_BGR2GRAY) |
| 14 | +edges=cv2.adaptiveThreshold(gray_image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,9,9) |
| 15 | + |
| 16 | +# Combine the smoothened image and the edge mask to create a cartoon-like effect. |
| 17 | +to_cartoon=cv2.bitwise_and(smoothened_image,smoothened_image,mask=edges) |
| 18 | + |
| 19 | +# Save the cartoon image in our current directory. A new Image would be generated in your current directory. |
| 20 | +cartooned_image=f"cartooned_{image_name}" |
| 21 | +cv2.imwrite(cartooned_image,to_cartoon) |
| 22 | + |
| 23 | +# Display the result. |
| 24 | +cv2.imshow("Cartooned Image",to_cartoon) |
| 25 | +cv2.waitKey(0) |
| 26 | +cv2.destroyAllWindows() |
| 27 | + |
| 28 | + |
| 29 | +# In this function, we accept user's argument from the terminal. -i or --image to specify the image. |
| 30 | +defget_image_argument(): |
| 31 | +parser=argparse.ArgumentParser(description="Please specify an image to 'cartoonify'.") |
| 32 | +parser.add_argument('-i','--image',help="Please use -h or --help to see usage.",dest='image') |
| 33 | +argument=parser.parse_args() |
| 34 | + |
| 35 | +ifnotargument.image: |
| 36 | +print("[-] Please specify an image. Use --help to see usage.") |
| 37 | +sys.exit()# Exit the program |
| 38 | + |
| 39 | +returnargument |
| 40 | + |
| 41 | + |
| 42 | +# We get the user's input (image) from the terminal and pass it into cartoonizer function. |
| 43 | +image_args=get_image_argument() |
| 44 | +cartoonizer(image_args.image) |