0
点赞
收藏
分享

微信扫一扫

Python OpenCV真香——去除照片白色背景


最近帮别人做了个图像分类的项目,他告诉我就是个二分类,区分有没有瑕疵,我想这简单就接了。

  我理想中的图片是这样的:

Python OpenCV真香——去除照片白色背景_tensorflow

然而现实中的图片确是这样的:

Python OpenCV真香——去除照片白色背景_opencv_02

这个不算夸张,还有更夸张的,物体占比非常小,大片的白色背景上还有一些污渍。

这给分类造成了很大的困扰,所以第一步是要把背景去掉,废话不多说,直接上代码。

import cv2

import numpy as np

img=cv2.imread(​'01.jpg'​)

## (1) Convert to gray, and threshold

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

print(gray)

#二值化,将背景150到255的像素值改为255

th, threshed = cv2.threshold(gray, 150, 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 = 255-img[y:y+h, x:x+w]

cv2.imwrite(​"001.png"​, dst)

结果:

Python OpenCV真香——去除照片白色背景_opencv_03


举报

相关推荐

0 条评论