如何裁剪或删除图像中的白色背景 [英] How to crop or remove white background from an image

查看:155
本文介绍了如何裁剪或删除图像中的白色背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to compare images using OpenCV and Python.

考虑以下图片:

两双鞋均相同,设置为白色背景.唯一的区别是,第一个具有比第二个更高的背景.

Both feature an identical pair of shoes, set to a white background. The only difference being that the first has a taller background than the second.

我想知道如何以编程方式裁剪两个鞋的白色背景,这样我只剩下一双鞋.

I want to know how to programmatically crop the white backgrounds of both so that I'm left with only the pair of shoes.

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

I must add that it won't be possible for me to manually crop the backgrounds.

推荐答案

您在注释中的要求:The shoes are on a white background. I would like to completely get rid of the border; as in be left with a rectangular box with either a white or a transparent background, having the length and width of the shoes in the picture.

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

Then my steps to crop the target regions:

  1. 转换为灰色,并设置阈值
  2. Morph-op消除噪音
  3. 找到最大区域轮廓
  4. 裁剪并保存
  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)

结果:

这篇关于如何裁剪或删除图像中的白色背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆