使用OpenCV裁剪黑色边缘 [英] Crop black edges with OpenCV

查看:1411
本文介绍了使用OpenCV裁剪黑色边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这应该是一个非常简单的问题,但我无法找到解决方案或有效的搜索关键字。

I think it should be a very simple problem, but I cannot find a solution or an effective keyword for search.

我只有这个图像。

黑色边缘没用,所以我想剪掉它们,只留下Windows图标(和蓝色背景)。

The black edges are useless so that I want to cut them, only leaving the Windows icon (and the blue background).

我不想要计算Windows图标的坐标和大小。 GIMP和Photoshop有一些autocrop功能。 OpenCV没有?

I do not want to calculate the coordinate and the size of the Windows icon. GIMP and Photoshop have sort of autocrop function. OpenCV does not have one?

推荐答案

我不确定你的所有图片是否都是这样的。但是对于这个图像,下面是一个简单的python-opencv代码来裁剪它。

I am not sure whether all your images are like this. But for this image, below is a simple python-opencv code to crop it.

第一个导入库:

import cv2
import numpy as np

Read图像,将其转换为灰度,并在二进制图像中生成阈值1。

Read the image, convert it into grayscale, and make in binary image for threshold value of 1.

img = cv2.imread('sofwin.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_,thresh = cv2.threshold(gray,1,255,cv2.THRESH_BINARY)

现在找到轮廓。只有一个对象,所以找到它的边界矩形。

Now find contours in it. There will be only one object, so find bounding rectangle for it.

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
x,y,w,h = cv2.boundingRect(cnt)

现在裁剪图像,并将其保存到另一个文件中。

Now crop the image, and save it into another file.

crop = img[y:y+h,x:x+w]
cv2.imwrite('sofwinres.png',crop)

以下是结果:

这篇关于使用OpenCV裁剪黑色边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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