目录
说明:
先扣取颜色模板图像为tar.jpg,再在目标图像中获取与模板颜色接近的区域并提取出来;
可以用做颜色分割或者其它目标检测或者分割算法的预处理步骤;
运算速度快,原理容易懂也可以卡阈值;
代码实现:
import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
# roi is the object or region of object we need to find
roi = cv.imread('tar.jpg')
hsv = cv.cvtColor(roi, cv.COLOR_BGR2HSV)
# target is the image we search in
target = cv.imread('ori.jpg')
hsvt = cv.cvtColor(target, cv.COLOR_BGR2HSV)
# calculating object histogram
# 图像hsv,第一通道和第二通道,没有mask,分成多少份(h范围就是到180,所以现在bin是1),从0-180的像素
roihist = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
# normalize histogram and apply backprojection
cv.normalize(roihist, roihist, 0, 255, cv.NORM_MINMAX)
dst = cv.calcBackProject([hsvt], [0, 1], roihist, [0, 180, 0, 256], 1)
# Now convolute with circular disc
disc = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
cv.filter2D(dst, -1, disc, dst)
# threshold and binary AND
ret, thresh = cv.threshold(dst, 0, 255, 0)
thresh = cv.merge((thresh, thresh, thresh))
res = cv.bitwise_and(target, thresh)
#显示出来源图像,图像mask和抠图结果
res = np.vstack((target, thresh, res))
cv.imwrite('res.jpg', res)
参考:
1、 https://zhuanlan.zhihu.com/p/166091178
2、OpenCV帮助文档