python-opencv boundingRect使用注意

來源:互聯網
上載者:User

標籤:tle   body   min   import   either   矩陣   綠色   注意   png   

矩形邊框(Bounding Rectangle)是說,用一個最小的矩形,把找到的形狀包起來。還有一個帶旋轉的矩形,面積會更小,效果見

上代碼

首先介紹下cv2.boundingRect(img)這個函數

這個函數很簡單,img是一個二值圖,也就是它的參數;

返回四個值,分別是x,y,w,h;

x,y是矩陣左上點的座標,w,h是矩陣的寬和高

然後利用cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)畫出矩行

參數解釋

第一個參數:img是原圖

第二個參數:(x,y)是矩陣的左上點座標

第三個參數:(x+w,y+h)是矩陣的右下點座標

第四個參數:(0,255,0)是畫線對應的rgb顏色

第五個參數:2是所畫的線的寬度

# 用綠色(0, 255, 0)來畫出最小的矩形架構x, y, w, h = cv2.boundingRect(cnt)cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)# 用紅色表示有旋轉角度的矩形架構rect = cv2.minAreaRect(cnt)box = cv2.cv.BoxPoints(rect)box = np.int0(box)cv2.drawContours(img, [box], 0, (0, 0, 255), 2)cv2.imwrite(‘contours.png‘, img)
但是要是在Python中使用,沒有vector或者mat作為boundingRect的輸入,會出現以下報錯:
    x, y, w, h = cv2.boundingRect(landmarks)TypeError: points is not a numpy array, neither a scalar

 

上面的landmark作為輸入是一個list,
解決方案:
因此需要引入numpy對他進行強轉,具體操作如下:

import  numpy as np x, y, w, h = cv2.boundingRect(np.array(landmarks))  cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

 


這樣就可以把list轉成array。







python-opencv boundingRect使用注意

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.