我想将area的值放在矩形的顶部。我尝试了很多方法,但是失败了
import numpy as np
import cv2
import time
font = cv2.FONT_HERSHEY_SIMPLEX
pic=cv2.imread('multiple.jpg')
picGray=cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY)
picBlur= cv2.GaussianBlur(picGray, (21, 21), 0)
_,contours,_=cv2.findContours(picBlur,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
contours=np.array(contours)
for i in range(len(contours)):
area=cv2.contourArea(contours[i])
print(area)
for cnt in contours:
cv2.drawContours(pic,cnt,-1,(0,255,0),2)
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(pic,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(pic,str(area),(x,y-5), font, .5,(255,255,255),1,cv2.LINE_AA)
cv2.imshow('pic',pic)
图片文件“ multiple.jpg”
答案 0 :(得分:1)
以下代码对我有用。
import cv2
font = cv2.FONT_HERSHEY_SIMPLEX
pic=cv2.imread('multiple.jpg')
picGray=cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY)
picBlur= cv2.GaussianBlur(picGray, (21, 21), 0)
contours, hierarchy = cv2.findContours(picBlur,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)
for cnt in contours:
area=cv2.contourArea(cnt)
print(area)
cv2.drawContours(pic,cnt,-1,(0,255,0),2)
x,y,w,h = cv2.boundingRect(cnt)
cv2.rectangle(pic,(x,y),(x+w,y+h),(0,255,0),2)
cv2.putText(pic,str(area),(x,y-5), font, .5,(255,255,255),1,cv2.CV_AA)
cv2.imshow('pic',pic)
cv2.waitKey()
cv2.destroyAllWindows()
我改编了:
_, contours, _
更改为contours, hierarchy
(因此,contours
的输出是不正确的,至少对于我的openCV版本是2.4.13.6),np.array(contours)
行和cv2.waitkey()
(使用cv2.imshow()
时必不可少!)和cv2.destroyAllWindows()