gpt4 book ai didi

python - 如何裁剪或删除图像中的白色背景

转载 作者:太空狗 更新时间:2023-10-29 22:14:43 24 4
gpt4 key购买 nike

我正在尝试使用 OpenCV 和 Python 比较图像。

考虑这些图像:


Image  900 x 726


Image 900 x 675


两者都有一双相同的鞋子,设置为白色背景。唯一的区别是第一个的背景比第二个高。

我想知道如何以编程方式裁剪两者的白色背景,以便我只剩下那双鞋。

我必须补充一点,我无法手动裁剪背景。

最佳答案

你在评论中的要求:鞋子是白色背景的。我想彻底摆脱边界;如留下一个白色或透明背景的矩形框,具有图片中鞋子的长度和宽度。

然后我裁剪目标区域的步骤:

  1. Convert to gray, and threshold
  2. Morph-op to remove noise
  3. Find the max-area contour
  4. Crop and save it
#!/usr/bin/python3
# Created by Silencer @ Stackoverflow
# 2018.01.23 14:41:42 CST
# 2018.01.23 18:17:42 CST
import cv2
import numpy as np

## (1) Convert to gray, and threshold
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
th, threshed = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)

## (2) Morph-op to remove noise
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11,11))
morphed = cv2.morphologyEx(threshed, cv2.MORPH_CLOSE, kernel)

## (3) Find the max-area contour
cnts = cv2.findContours(morphed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
cnt = sorted(cnts, key=cv2.contourArea)[-1]

## (4) Crop and save it
x,y,w,h = cv2.boundingRect(cnt)
dst = img[y:y+h, x:x+w]
cv2.imwrite("001.png", dst)

结果:

关于python - 如何裁剪或删除图像中的白色背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48395434/

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