python基础教程:python使用numpy实现直方图反向投影示例

@本文来源于公众号:csdn2299,喜欢可以关注公众号 程序员学府
最近跟着OpenCV2-Python-Tutorials在学习python_opencv中直方图的反向投影时,第一种方法是使用numpy实现将图中的红色玫瑰分割出来,教程给的代码缺了一句函数,导致实现不出来。

自己加上了后(也不知到这样加对不对)代码和效果如下:

import cv2
import numpy as np
roi = cv2.imread('./data/rose_red.jpg')
hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)
#target is the image we search in
target = cv2.imread('./data/rose.jpg')
cv2.imshow('target',target)
hsvt = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)
# Find the histograms using calcHist. Can be done with np.histogram2d also
M = cv2.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )
print(M)
I = cv2.calcHist([hsvt],[0, 1], None, [180, 256], [0, 180, 0, 256] )
h,s,v = cv2.split(hsvt)
#斜体是自己加上的
R=M/I
print(R.shape)
B = R[h.ravel(),s.ravel()]
print(B)
B = np.minimum(B,1)
print(B)
B = B.reshape(hsvt.shape[:2])
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(9,9))
B=cv2.filter2D(B,-1,disc)
B = np.uint8(B)
cv2.normalize(B,B,0,255,cv2.NORM_MINMAX)
cv2.imshow('B',B)
ret,thresh = cv2.threshold(B,2,255,0)
cv2.imshow('thresh',thresh)
res = cv2.bitwise_and(target,target,mask=thresh)
cv2.imshow('res',res)
cv2.waitKey(0)

效果:在这里插入图片描述

非常感谢你的阅读
大学的时候选择了自学python,工作了发现吃了计算机基础不好的亏,学历不行这是
没办法的事,只能后天弥补,于是在编码之外开启了自己的逆袭之路,不断的学习python核心知识,深入的研习计算机基础知识,整理好了,如果你也不甘平庸,那就与我一起在编码之外,不断成长吧!
其实这里不仅有技术,更有那些技术之外的东西,比如,如何做一个精致的程序员,而不是“屌丝”,程序员本身就是高贵的一种存在啊,难道不是吗?[点击加入]想做你自己想成为高尚人,加油!

发布了10 篇原创文章 · 获赞 0 · 访问量 2787

猜你喜欢

转载自blog.csdn.net/chengxun03/article/details/105376273