'How to put Pytesseract OCR on the web

I am using Pytesseract OCR for text detection and I am using a jupyter notebook to run it right now so the output is just popping up as another window. My output for the program is an image and I was wondering if there is a way to use flask or django or something to put my program on a website.

I am trying to allow the user to input their own image and then the program will output another image on the website.

This is the main code:

def pytess(img):

   hImg,wImg,_ = img.shape
   boxes = pytesseract.image_to_boxes(img)
   for b in boxes.splitlines():
       print(b[0])
       b = b.split(' ')
       x,y,w,h= int(b[1]),int(b[2]),int(b[3]),int(b[4])
       cv2.rectangle(img,(x,hImg-y),(w,hImg-h),(0,0,255), 2)
       cv2.putText(img,b[0],(x,hImg-y+25), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2)



   ##Detecting Words
   hImg,wImg,_ = img.shape
   boxes = pytesseract.image_to_data(img)
   for x,b in enumerate(boxes.splitlines()):
       if x!=0:
           b = b.split()
           if len(b)==12:
               x,y,w,h= int(b[6]),int(b[7]),int(b[8]),int(b[9])
               cv2.rectangle(img,(x,y),(w+x,h+y),(0,0,255), 2)
               cv2.putText(img,b[11],(x,y), cv2.FONT_HERSHEY_COMPLEX,1,(50,50,255),2)


   cv2.imshow("Result",img)
   cv2.waitKey(0)
pytess(img)


Solution 1:[1]

Flask would definitely work for this. You could use a POST request that takes in an image file and then returns an image with the OCR applied.

from flask import Flask, request, Response

# Initialize Flask application
app = Flask(__name__)

# POST request for running OCR
@app.route('/ocr', methods= ['POST'])
def run_ocr():
    image = request.files["image"]
    # Read the image via file.stream, returns PIL image (may need to convert)
    img = Image.open(image.stream)
    # run ocr on image (you will need to update your function to return img)
    processed_img = pytess(img)
    # prepare image for response
    _, img_encoded = cv2.imencode('.png', processed_img)
    response = img_encoded.tostring()
    # return png img with OCR shown
    return Response(response=response, status=200, mimetype='image/png')

if __name__ == "__main__":
    app.run(debug=True)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 The AI Guy