简体   繁体   中英

python cv2 puttext - error while showing the variable

I'm writing one of my first codes and I want to show variable on image. Variable is read from textfile. Here is part of my code:

font=cv2.FONT_HERSHEY_SIMPLEX
fontScale=2
fontColor=(255,255,255)
lineType=2;

def line11():
    cv2.ellipse(img, (443,350), (35,35), 0, 0, -180, (0,0,255), 4);
    cv2.putText(img, x,(443,320),fontScale, (255,255,255),lineType)

Reading value x from texfile:

with open('US1.txt') as f1, open('US2.txt') as f2: 
    for x, y in zip(f1,f2):
        x = x.strip()
        y = y.strip()
        print("{0} {1}".format(x, y))

Unfortunately, I got the error:

TypeError                                 
Traceback (most recent call last)
<ipython-input-2-bc1d3b9f83c2> in <module>
    130 
    131         if (float(x) <=0.5):
--> 132             line11();
    133 
    134         elif (0.5< float(x)<=1):

<ipython-input-2-bc1d3b9f83c2> in line11()
     16     cv2.ellipse(img, (443,350), (35,35), 0, 0, -180, (0,0,255), 4);
     17 
---> 18     cv2.putText(img, x, (443,350),fontScale, (255,255,255),lineType)
     19 
     20 def line12():

TypeError: must be real number, not tuple

I can't find a solution. I tried many options (ie chinging type of x), now I'm helpless. Can somebody explain it to me? Thank you!

You missed the font argument. Try this:

font=cv2.FONT_HERSHEY_SIMPLEX
fontScale=2
fontColor=(255,255,255)
lineType=cv2.line_AA
org=(443,320)
text = str(x)

cv2.putText(img, text,org,font,fontScale,fontColor,lineType)

Refer here

I guess the error is because you forgot to mention font on putText function. The tuple it got was (255,255,255), while it was expecting fontScale .

cv2.putText(image, text, org, font, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])

Try: cv2.putText(img, x,(443,320),font, fontScale, fontColor,lineType)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM