Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

python - 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 want to keep; anything outside I want to crop out. Is there a python opencv code that would do it for me? I've been trying to figure it out using opencv by playing around with thresholds but it's just not doing it for me.

Original image:

enter image description here The area that I want to keep (the space I want to keep is highlighted by green arrows): enter image description here

Desired output: enter image description here

Thank you so much

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 python3

import 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...