巧妙的颜色分割方法-基于颜色模板再也不用自己卡颜色值

本文介绍了一种使用OpenCV进行颜色模板匹配的方法,用于从目标图像中提取与模板颜色相似的区域,适用于颜色分割和目标检测。通过计算HSV直方图、归一化和背投影,快速定位并提取目标,配合阈值处理和二值操作,实现了高效的目标定位。
摘要由CSDN通过智能技术生成

目录

说明:

代码实现:


说明:

先扣取颜色模板图像为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帮助文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值