Home > Back-end >  I am having a problem with making my code more concise in opencv
I am having a problem with making my code more concise in opencv

Time:12-28

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))

My end goal is to draw boxes around each letter in the image using cv2.rectangle(i, (x, himg-y), (w, himg h)). Pls help with the last 2 lines. I want it as consize as possible

CodePudding user response:

To draw boxes around each letter in the image, you can use a loop to iterate over the list of bounding boxes and draw a rectangle for each one:

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)

Complete code:

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()
  • Related