在opencv中使代码更简洁时遇到问题

7rtdyuoh  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(99)
import cv2
import pytesseract
pytesseract.pytesseract.tesseract_cmd="D:\\Tesseract\\tesseract.exe"
i = cv2.imread('1.png')
himg,wimg,_ = i.shape
k= [b.split(' ') for b in pytesseract.image_to_boxes(i).splitlines()]
for x,y,w,h in  [int(x) for x in [a[1],a[2],a[3],a[4]] for a in k] :
    cv2.rectangle(i, (x, himg-y), (w, himg + h))

我的最终目标是用cv2.rectangle(i,(x,himg-y),(w,himg + h))在图像中的每个字母周围画出方框。请帮助最后2行。我希望它尽可能的一致

goqiplq2

goqiplq21#

若要在图像中的每个字母周围绘制方框,可以使用循环遍历边框列表,并为每个边框绘制一个矩形:

for box in k:
    x, y, w, h = box[1], box[2], box[3], box[4]
    cv2.rectangle(i, (x, y), (x+w, y+h), (0, 255, 0), 2)

完整代码:

import cv2
import pytesseract

# Set the path to the Tesseract executable
pytesseract.pytesseract.tesseract_cmd = "D:\\Tesseract\\tesseract.exe"

# Read the image
i = cv2.imread('1.png')

# Extract the bounding boxes for each letter in the image
k = [b.split(' ') for b in pytesseract.image_to_boxes(i).splitlines()]

# Iterate over the bounding boxes and draw a rectangle around each letter
for box in k:
    x, y, w, h = box[1], box[2], box[3], box[4]
    cv2.rectangle(i, (x, y), (x+w, y+h), (0, 255, 0), 2)

# Show the image
cv2.imshow('image', i)
cv2.waitKey(0)
cv2.destroyAllWindows()

相关问题