Pet*_*sen 0 python opencv crop image-processing python-imaging-library
我有一个程序,使用 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')
Run Code Online (Sandbox Code Playgroud)
来自另一台计算机的另一张图像需要裁剪到同一查看器:
这是使用 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)
Run Code Online (Sandbox Code Playgroud)
阈值图像:
裁剪结果:
裁剪(x,y,w,h):
48 368 1578 801
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2923 次 |
| 最近记录: |