How do you crop a PNG image in python?

I have successfully managed to extract a skin patch from a facial image. However; for my task, I don't need the bottom eye and eyelash part. Is there a way to crop the following png image from the top at a slight angle? The resultant image should be in PNG format. I want to crop the area above the red line:

Desired Image

1 answer

  • answered 2021-05-03 21:20 Ann Zen

    As long as you have the color values of the line of which you want to crop above of, you can do something like this:

    import cv2
    import numpy as np
    
    img = cv2.imread("image.png")
    
    for i, j in zip(*np.where(np.all(img == [0, 0, 253], 2))):
        img[:i, j] = 0
    
    cv2.imshow("Image", img)
    cv2.waitKey(0)
    

    Output:

    enter image description here

    Explanation:

    1. Import the necessary libraries:
    import cv2
    import numpy as np
    
    1. Read in the image:
    img = cv2.imread("image.png")
    
    1. Loop though the indices of the image where the BGR value of the pixel at the indices is the BGR value of the line's color:
    for i, j in zip(*np.where(np.all(img == [0, 0, 253], 2))):
    
    1. Set all the pixels before the outer index at the inner index to black. If you were to visualize it it would be drawing black vertical lines one by one:
        img[:i, j] = 0
    
    1. Show the resulting image:
    cv2.imshow("Image", img)
    cv2.waitKey(0)