使用Python从OpenCV中扫描裁剪矩形照片

问题描述 投票:0回答:1

我有一堆像这样的照片:

Asakusa photo scan

我想自动裁剪图像,以便只显示照片(可能还有标题)。

我试过检测轮廓,但他们发现照片中的物体边界而不是照片本身。对于图像的边缘以及其他小的边缘,也存在伪轮廓。

Bad contours

我该怎么做才能得到包含照片的矩形?

python opencv image-processing
1个回答
2
投票

我设法找到了一个令人满意的解决方案。有几个步骤:

  1. 获得轮廓
  2. 去除面积太小或太大的轮廓
  3. 找到所有剩余轮廓的最小/最大x / y
  4. 使用这些值创建要裁剪的矩形

这是基本过程。

无论如何,这里是核心部分的一些代码:

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

这有重要的部分,但我使用了另外两个适用于我的数据集的技巧:

  1. 修改阈值,直到图像的某个百分比为黑色。对于我的大多数图像,即使照片中最轻的部分比下面的页面更暗,因此在某个魔术阈值水平下,照片变成黑色正方形,因此更容易获得良好的轮廓。
  2. 完全忽略图像边缘附近的轮廓。有时书的一些书脊会在原始图像的边界处形成轮廓,这是不合需要的。检查边缘的小像素数(如20)内的轮廓并忽略它们解决了这个问题。

一些结果图像,左边是原始图像,右边是自动裁剪的:

Street with streetcar

People in a park

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.