如何根据复杂的标准裁剪图像? [英] How to crop an image based on a complex criteria?

查看:109
本文介绍了如何根据复杂的标准裁剪图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组类似的图像,如下图所示.我想将图像的一部分保留在顶部的红色不规则"矩形内(绿色箭头代表我要保留的空间;我想裁剪掉的任何外部物体.是否有python opencv代码可以做到这一点?我吗?我一直在尝试通过使用opencv来解决阈值问题,但这并不是为我做的事.

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.

原始图片:

我要保留的区域(我要保留的空间用绿色箭头突出显示):

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

所需的输出:

非常感谢您

推荐答案

这就是我的方法.进行cv2.imwrite()的代码仅用于调试,因此您可以看到各个阶段,我将临时的中间图像放置在其中,但是您可以将所有代码块附加在一起,以形成一个连续的一段代码:

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)

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

# 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)

这篇关于如何根据复杂的标准裁剪图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆