如何使用 OpenCV 从屏幕截图中裁剪图像?

How to crop an image from screenshot with the use of OpenCV?

我最近开始学习图像处理并接受了一个任务,我需要通过使用 OpenCV 从移动 Instagram 屏幕截图中裁剪图像。我需要使用轮廓和裁剪找到图像的边缘,但我不确定如何正确执行此操作。

我试着查找了一些这样的例子:

https://www.quora.com/How-can-I-detect-an-object-from-static-image-and-crop-it-from-the-image-using-openCV

How to crop rectangular shapes in an image using Python

但我还是不明白我的情况该怎么做。

基本上我有这样的图片:

https://imgur.com/a/VbwCdkOhttps://imgur.com/a/Mm69i35

结果应该是这样的:

https://imgur.com/a/Bq6Zjw0

https://imgur.com/a/AhzOkWS

使用的截图只需要来自移动版Instagram,并且可以假设它们总是矩形的

如果有不止一张这样的图片:

https://imgur.com/a/avv8Wvv

然后只裁剪两者之一(哪个无所谓)。 例如:

https://imgur.com/a/a4KnRKC

谢谢!

您的快照图像的显着特征之一是白色背景。一切都出现在它上面,甚至是那个用户图像。因此,我们将尝试分割出背景,这会给我们留下较小的组件,例如 Instagram 图标、喜欢等。然后我们将选择最大的元素,假设用户图像是屏幕上出现的最大元素。然后我们将简单地找到最大轮廓的 cv2.boundingRect() 并相应地裁剪快照:

import cv2
import numpy as np

img = cv2.imread("/path/to/img.jpg")

white_lower = np.asarray([230, 230, 230])
white_upper = np.asarray([255, 255, 255])

mask = cv2.inRange(img, white_lower, white_upper)
mask = cv2.bitwise_not(mask)

现在我们在这个蒙版中填充查找轮廓,select 最大的一个。

im, cnt, hierarchy = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
largest_contour = max(cnt, key=lambda x:cv2.contourArea(x))
bounding_rect = cv2.boundingRect(largest_contour)

cropped_image = img[bounding_rect[1]: bounding_rect[1]+bounding_rect[3],
                bounding_rect[0]:bounding_rect[0]+bounding_rect[2]]