Python,OpenCV進行直方圖反投影
- 1. 效果圖
- 2. 原始碼
- 參考
這篇博客將介紹Python,OpenCV中的直方圖反投影,直方圖反投影用于影像分割或在影像中查找感興趣的物件, 簡單地說,它創建了一個與輸入影像大小相同(但只有一個通道)的影像,其中每個像素對應于該像素屬于感興趣物件的概率,輸出影像將使感興趣的物件比其余部分更白,如提取影像中的地面;
顏色直方圖優于灰度直方圖,因為物體的顏色比灰度強度更好地定義物體,
1. 效果圖
如下官方的提取地面的效果圖如下:

2. 原始碼
import cv2
import numpy as np
# ROI是感興趣區域
roi = cv2.imread('rose_red.png')
hsv = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
# 需要尋找的ROI物件
target = cv2.imread('rose.png')
hsvt = cv2.cvtColor(target, cv2.COLOR_BGR2HSV)
# 計算ROI物件的直方圖 cv.calcHist np.histogram2d np.binscount
roihist = cv2.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
# 直方圖均衡化,并應用反投影
cv2.normalize(roihist, roihist, 0, 255, cv2.NORM_MINMAX)
dst = cv2.calcBackProject([hsvt], [0, 1], roihist, [0, 180, 0, 256], 1)
# 用橢圓進行卷積
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
cv2.filter2D(dst, -1, disc, dst)
# 閾值化并使用按位與
ret, thresh = cv2.threshold(dst, 50, 255, 0)
thresh = cv2.merge((thresh, thresh, thresh))
res = cv2.bitwise_and(target, thresh)
res = np.vstack((target, thresh, res))
cv2.imwrite('res.jpg', res)
參考
- https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_histograms/py_histogram_backprojection/py_histogram_backprojection.html#histogram-backprojection
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/289467.html
標籤:AI
