You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用EasyOCR做文本检测遇cv2.rectangle参数错误,求技术支持

EasyOCR文本检测中cv2.rectangle参数错误解决方案

基于EasyOCR开展文本检测项目时,运行代码触发cv2.rectangle参数错误,报错信息如下:

cv2.error: OpenCV(4.5.2) :-1: error: (-5:Bad argument) in function 'rectangle'
Overload resolution failed:

  • Can't parse 'pt1'. Sequence item with index 0 has a wrong type
  • Can't parse 'pt1'. Sequence item with index 0 has a wrong type
  • Can't parse 'rec'. Expected sequence length 4, got 2
  • Can't parse 'rec'. Expected sequence length 4, got 2

用户代码:

import cv2
import numpy as np
from matplotlib import pyplot as plt
import easyocr


cap = cv2.VideoCapture(0)
reader = easyocr.Reader(['en'], gpu = True)

while True :
    _, frame = cap.read()
    result = reader.readtext(frame)
    for detection in result:
        top_left = tuple(detection[0][0])
        bottom_right = tuple(detection[0][2])
        text = detection[1]
        print (text)
        img = cv2.rectangle(frame,top_left,bottom_right,(0,255,0),2)
    cv2.imshow("Text Recognition", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

问题原因

EasyOCR返回的坐标是浮点数类型,而OpenCV的rectangle函数要求坐标必须是整数类型的元组,类型不匹配导致参数解析失败。

解决方案

将坐标中的浮点数转为整数,修改代码中坐标转换的部分:

top_left = tuple(map(int, detection[0][0]))
bottom_right = tuple(map(int, detection[0][2]))

完整修正后的代码:

import cv2
import numpy as np
from matplotlib import pyplot as plt
import easyocr


cap = cv2.VideoCapture(0)
reader = easyocr.Reader(['en'], gpu = True)

while True :
    _, frame = cap.read()
    result = reader.readtext(frame)
    for detection in result:
        # 将浮点数坐标转为整数元组
        top_left = tuple(map(int, detection[0][0]))
        bottom_right = tuple(map(int, detection[0][2]))
        text = detection[1]
        print(text)
        img = cv2.rectangle(frame, top_left, bottom_right, (0,255,0), 2)
    cv2.imshow("Text Recognition", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

map(int, ...)会遍历坐标中的每个浮点数元素并转为整数,再通过tuple()包装成符合OpenCV要求的参数类型,即可解决该错误。

内容的提问来源于stack exchange,提问作者Arif Fadillah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 11:55:26