gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:40:58 25 4
gpt4 key购买 nike

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

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

How to crop biggest rectangle out of an image

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

How to detect edge and crop an image in Python

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)

enter image description here

现在我们在此蒙版中填充查找轮廓并选择最大的一个。

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]]

enter image description here

关于python - 如何使用 OpenCV 从屏幕截图中裁剪图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53942620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com