[英]Putting text using cv2.putText() outside a loop
I want to put values of area on top of the rectangle. 我想将面积的值放在矩形的顶部。 I tried many ways, but failed
我尝试了很多方法,但是失败了
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)
Image file 'multiple.jpg' 图像文件“ multiple.jpg”
The code below works for me. 下面的代码对我有用。
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()
I adapted: 我改编了:
_, contours, _
to contours, hierarchy
(so your output of contours
wasn't correct, at least for my version of openCV, 2.4.13.6), _, contours, _
更改为contours, hierarchy
(因此, contours
的输出是不正确的,至少对于我的openCV版本2.4.13.6而言), np.array(contours)
line and np.array(contours)
行并 cv2.waitkey()
(necessary when using cv2.imshow()
!!) and cv2.destroyAllWindows()
cv2.waitkey()
(使用cv2.imshow()
时cv2.imshow()
!)和cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.