使用cv2.putText()在循环外放置文本

时间:2018-12-25 20:01:59

标签: python python-3.x image opencv

我想将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”

1 个答案:

答案 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()

我改编了:

  • 第一个for循环
  • _, contours, _更改为contours, hierarchy(因此,contours的输出是不正确的,至少对于我的openCV版本是2.4.13.6),
  • 跳过了np.array(contours)行和
  • 添加了cv2.waitkey()(使用cv2.imshow()时必不可少!)和cv2.destroyAllWindows()