?外接矩形、外接圓:
1 import cv2 2 import numpy 3 4 img = cv2.imread('../img/img.png', -1) 5 ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) 6 contours, hier = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 7 8 for c in contours: 9 # 尋找平行于 x軸、y軸 的外接矩形坐標(biāo) -> 左上角坐標(biāo)、寬度、高度 10 rectangle = cv2.boundingRect(c) 11 x, y, w, h = rectangle 12 # 繪制外接矩形 13 cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) 14 15 # 尋找包含前景圖的 可旋轉(zhuǎn) 最小外接矩形 -> 中心點坐標(biāo)、寬度、高度 16 rect = cv2.minAreaRect(c) 17 # 尋找旋轉(zhuǎn)矩形的四個頂點 -> 左上角、右上角、右下角和左下角的頂點坐標(biāo) 18 box = cv2.boxPoints(rect) 19 # 取整 20 box = numpy.int0(box) 21 # 繪制外接矩形,對box打包成列表是因為drawContours希望接收為tuple or list 22 # 或者說是一個iterable 23 cv2.drawContours(img, [box], 0, (0, 0, 255), 3) 24 25 # 計算最小外接圓 -> 圓心坐標(biāo)、半徑 26 (x, y), radius = cv2.minEnclosingCircle(c) 27 # 取整 28 center = int(x), int(y) 29 radius = int(radius) 30 # 繪制圓形 31 img = cv2.circle(img, center, radius, (0, 255, 0), 2) 32 33 34 img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) 35 img = cv2.drawContours(img, contours, -1, (0, 255, 0), 2) 36 cv2.imshow('', img) 37 cv2.waitKey() 38 cv2.destroyAllWindows()
?文章來源地址http://www.zghlxwxcb.cn/news/detail-748642.html
1、cv2.boundingRect() Method 和 cv2.minAreaRect() Merhod:前者只尋找和 x、y軸 平行的矩形,后者則可以出現(xiàn)旋轉(zhuǎn)角度。
2、cv2.drawContours() Method:第二個參數(shù)接收的是輪廓信息,但是這個輪廓信息需要以 tuple or list or set類型(或者說是iterable)才可以傳入。
請注意:當(dāng)我們對 box 變量進行 tuple() list() set() 操作時,都會報錯,這是因為,在針對numpy數(shù)組進行可迭代轉(zhuǎn)換時,前面的三種方式,都會對numpy數(shù)組中的每個元素都視為單獨的一個 ”列表元素“?,而不是將整個 box 視為一個列表 這會導(dǎo)致如:
box =?[[ -8 410] [ 57 -21] [444 37] [379 469]],
在使用 list() 后:
box =?[array([ -8, 410], dtype=int64), array([ 57, -21], dtype=int64), array([444,? 37], dtype=int64), array([379, 469], dtype=int64)]
但是我們需要的正確的格式是:
[array([[ -8, 410], [ 57, -21], [444, 37], [379, 469]], dtype=int64)]
?
總結(jié):針對numpy數(shù)組轉(zhuǎn)換為可迭代對象時,[ ]、(, )、{ } 和 list()、tuple()、set() 會得到不用的結(jié)果,即是否會將元素視為單獨的一個”列表元素“,這種情況只針對 numpy 數(shù)組(就筆者目前所接觸過的各種類型)。文章來源:http://www.zghlxwxcb.cn/news/detail-748642.html
?
到了這里,關(guān)于【Python】【OpenCV】繪制外接矩形、外接圓 以及 凸輪廓和Douglas-Peucker算法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!