python使用numpy实现直方图反向投影示例

yipeiwu_com5年前Python基础

最近跟着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)

效果:

rose_red.jpg

rose.jpg

result:

以上这篇python使用numpy实现直方图反向投影示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python中字符串的处理技巧分享

一、如何拆分含有多种分隔符的字符串? 实际案例 我们要把某个字符串依据分隔符号拆分不同的字符段,该字符串包含多种不同的分隔符,例如: s = 'asd;aad|dasd|dasd,...

pyqt和pyside开发图形化界面

复制代码 代码如下:#!/usr/bin/env pythonimport sysfrom PyQt4 import QtGui,QtCoreimport httplibfrom url...

python3 assert 断言的使用详解 (区别于python2)

python3 和python以前的版本有点不同 如果你断言的 语句正确 则什么反应都没有 但是如果你出错之后 就会报出 AssertionError 并且错误可以自己填写 格式 :...

Python简单连接MongoDB数据库的方法

本文实例讲述了Python连接MongoDB数据库的方法。分享给大家供大家参考,具体如下: Python使用pymongo操作MongoDB数据库,首先需要安装pymongo模块,如下示...

python通过正则查找微博@(at)用户的方法

本文实例讲述了python通过正则查找微博@(at)用户的方法。分享给大家供大家参考。具体如下: 这段代码用到了python正则的findall方法,查找所有被@的用户,使用数组形式返回...