import cv2
import numpy as np
ori = cv2.imread('../data/hua.png', 1)
cv2.imshow('ori', ori)
img = cv2.cvtColor(ori, cv2.COLOR_BGR2GRAY)
cv2.imshow('img', img)
ret, binary = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imshow('binary', binary)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
mask = np.zeros(ori.shape, np.uint8)
mask = cv2.drawContours(mask, contours, -1, (255, 255, 255), -1)
cv2.imshow('mask', mask)
loc = cv2.bitwise_and(ori, mask)
cv2.imshow('loc', loc)
cv2.waitKey()
cv2.destroyAllWindows()
cv2.imwrite('../data/mask.jpg', mask)
cv2.imwrite('../data/loc.jpg', loc)
注意点:
1-绘制轮廓必须是二值图像,且白色为前景色
原图
mask
loc
在不是高精度的抠图的使用上,这个方法还是有特定的抠图功能的