我有一堆像这样的照片:
我想自动裁剪图像,以便只显示照片(可能还有标题)。
我尝试检测轮廓,但他们发现照片中的物体边框而不是照片本身。图像的边缘以及其他小的边缘也有一个虚假的轮廓。
如何才能获得包含照片的矩形?
答案 0 :(得分:2)
我设法找到了一个令人满意的解决方案。有几个步骤:
这是基本过程。
无论如何,这里有一些核心部分的代码:
import cv2
from os.path import basename
from glob import glob
def get_contours(img):
# First make the image 1-bit and get contours
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 150, 255, 0)
cv2.imwrite('thresh.jpg', thresh)
img2, contours, hierarchy = cv2.findContours(thresh, 1, 2)
# filter contours that are too large or small
size = get_size(img)
contours = [cc for cc in contours if contourOK(cc, size)]
return contours
def get_size(img):
ih, iw = img.shape[:2]
return iw * ih
def contourOK(cc, size=1000000):
x, y, w, h = cv2.boundingRect(cc)
if w < 50 or h < 50: return False # too narrow or wide is bad
area = cv2.contourArea(cc)
return area < (size * 0.5) and area > 200
def find_boundaries(img, contours):
# margin is the minimum distance from the edges of the image, as a fraction
ih, iw = img.shape[:2]
minx = iw
miny = ih
maxx = 0
maxy = 0
for cc in contours:
x, y, w, h = cv2.boundingRect(cc)
if x < minx: minx = x
if y < miny: miny = y
if x + w > maxx: maxx = x + w
if y + h > maxy: maxy = y + h
return (minx, miny, maxx, maxy)
def crop(img, boundaries):
minx, miny, maxx, maxy = boundaries
return img[miny:maxy, minx:maxx]
def process_image(fname):
img = cv2.imread(fname)
contours = get_contours(img)
#cv2.drawContours(img, contours, -1, (0,255,0)) # draws contours, good for debugging
bounds = find_boundaries(img, contours)
cropped = crop(img, bounds)
if get_size(cropped) < 400: return # too small
cv2.imwrite('cropped/' + basename(fname), cropped)
process_image('pic.jpg')
这有重要的部分,但我使用了另外两个适用于我的数据集的技巧: