如何在 OpenCV 或 PIL 中自动找到一个矩形并裁剪

How to automatically find a rectangle and crop in OpenCV or PIL

我有一个程序可以使用 PIL 自动将一系列图像裁剪到特定区域。但是,当我 运行 使用不同尺寸显示器的屏幕截图时,裁剪区域在错误的位置。有没有办法使用 OpenCV 或 PIL 自动找到我想要裁剪的矩形(例如 Youtube 视频的主查看器)并裁剪到它,同时将图像保留为彩色,然后将图像保存到新的文件夹?

我的裁剪图片代码:

import os, random
from PIL import Image

files = []

for x in os.listdir():
    if '.jpg' in f'{x}' or '.png' in f'{x}' or '.jpeg' in f'{x}':
        files.append(x)
    else:
        print(f'Passed by {x}! It is not an image!')
for x in files:
    y = hex(random.randint(100000,500000))
    image = Image.open(f'{x}')
    newimage = image.crop((48,367,1626,1256))
    newimage.save(f'newdir/{y}.png')

示例图片(适用于 PIL 裁剪器):

我要的图片:

来自另一台计算机的另一张图片需要裁剪到同一查看器:

这是使用 Python/OpenCV 的一种方法。

基本上,对图像进行阈值处理,然后获取轮廓,然后获取最大轮廓的边界框并使用边界框进行裁剪。

输入:

import cv2
import numpy as np

# load image
img = cv2.imread("screen.jpg")

# get color bounds of white region
lower =(180,180,180) # lower bound for each channel
upper = (255,255,255) # upper bound for each channel

# threshold
threshold = cv2.inRange(img, lower, upper)

# get the largest contour
contours = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)

# get bounding box
x,y,w,h = cv2.boundingRect(big_contour)
print(x,y,w,h)


# crop the image at the bounds
crop = img[y:y+h, x:x+w]

# write result to disk
cv2.imwrite("screen_threshold.jpg", threshold)
cv2.imwrite("screen_cropped.jpg", crop)

# display it
cv2.imshow("threshold", threshold)
cv2.imshow("crop", crop)
cv2.waitKey(0)

阈值图像:

裁剪结果:

裁剪 (x,y,w,h):

48 368 1578 801