gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:21:10 24 4
gpt4 key购买 nike

我想将面积的值放在矩形的顶部。我尝试了很多方法,但是失败了

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”

最佳答案

下面的代码对我有用。

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(因此,至少对于我的openCV版本2.4.13.6,您的contours输出不正确),
  • 跳过了np.array(contours)行和
  • 添加了cv2.waitkey()(在使用cv2.imshow() !!时是必需的)和cv2.destroyAllWindows()
  • 关于python - 使用cv2.putText()在循环外放置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53925299/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com