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

查看:119
本文介绍了使用 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 具有某种自动裁剪功能.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

读取图像,将其转换为灰度,并以阈值为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天全站免登陆