Skip to content Skip to sidebar Skip to footer

How To Crop An Image Based On A Complex Criteria?

I have a set of similar images like the one below. I want to keep the portion of the image that is within the top red 'irregular' rectangle (green arrows represent the space that I

Solution 1:

Here's how I would do it. The code that does cv2.imwrite() is just for debug so you can see the various stages and I have put the temporary, intermediate images in where they are produced, but you can just take all the chunks of code and append them together to make one continuous piece of code:

#!/usr/bin/env python3import cv2
import numpy as np

# Load image
im = cv2.imread('wavy.png')
copy = im.copy()

# Flood fill with white starting from 10,10
cv2.floodFill(copy,mask=None,seedPoint=(10,10),newVal=(255,255,255))
cv2.imwrite('temp1.png',copy)

enter image description here

# Make everything not white into black
copy[~np.all(copy== (255, 255, 255), axis=-1)] = (0,0,0)
cv2.imwrite('temp2.png',copy)

enter image description here

# Make white all the bits we don't want at the bottom of the original image
im[:] |= ~copy

# Crop/trim part we want
Ynonzero, Xnonzero, _ = np.nonzero(copy)
res = im[np.min(Ynonzero):np.max(Ynonzero), np.min(Xnonzero):np.max(Xnonzero)]

# Save result
cv2.imwrite('result.png',res)

enter image description here

Post a Comment for "How To Crop An Image Based On A Complex Criteria?"