opencv 去除背景

过程:先拍一张背景图,然后待去除背景的图片减去背景,然后二值化,再调用findContours得到轮廓,然后把必要的轮廓合并起来,最后用boundingRect包起来,作为ROI区域保存该区域内的图片

https://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begin.html

http://blog.csdn.net/sunny2038/article/details/12889059

http://blog.csdn.net/zhangxb35/article/details/47275277

import cv2
import numpy as np
from matplotlib import pyplot as plt
import glob

import cv2
import numpy as np
from matplotlib import pyplot as plt
import glob

background = cv2.imread('background.bmp', 0)
files = sorted(glob.glob('*.bmp'))
for file in files:
    if file == 'background.bmp':
        continue
    
    img0 = cv2.imread(file, 0)
    img = img0 - background
    imageGray = cv2.GaussianBlur(img,(15,15),25);  
    ret,thresh = cv2.threshold(imageGray,127,255,cv2.THRESH_BINARY_INV)
    im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    
    cnt = np.row_stack((contours[i] for i in range(len(contours))))
    x, y, w, h = cv2.boundingRect(cnt)
    cv2.rectangle(img0, (x, y), (x+w, y+h), (255, 0, 0), 4)

    # cv2.drawContours(img, contours, len(contours)-1, (255,0,0), 3)
    # cv2.drawContours(img, contours, len(contours)-1, (255,0,0), 3)
    # print(len(contours))
    plt.imshow(img0)
    plt.show()

    img0 = cv2.imread(file)
    # roi = img0[x:x+w, y:y+h]
    roi = img0[y:y+h, x:x+w]
    cv2.imwrite(file.replace('bmp', 'jpg'), roi)
    


你可能感兴趣的:(opencv)