Facebook
From Cream Hedgehog, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 95
  1. import cv2
  2.  
  3. # Load the image
  4. img = cv2.imread('image.png')
  5.  
  6. # Convert the image to grayscale
  7. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  8.  
  9. # Apply thresholding to the grayscale image
  10. thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
  11.  
  12. # Find contours in the thresholded image
  13. contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  14.  
  15. # Initialize an empty list to store the detected text
  16. detected_text = []
  17.  
  18. # Loop over the contours
  19. for contour in contours:
  20.     # Compute the bounding box of the contour
  21.     x, y, w, h = cv2.boundingRect(contour)
  22.  
  23.     # Extract the ROI from the image
  24.     roi = img[y:y + h, x:x + w]
  25.  
  26.     # Apply OCR to the ROI
  27.     text = pytesseract.image_to_string(roi)
  28.  
  29.     # Add the detected text to the list
  30.     detected_text.append(text)
  31.  
  32. # Print the detected text
  33. print(detected_text)
  34.