OpenCV MSER detect text areas - Python OpenCV MSER detect text areas - Python python python

OpenCV MSER detect text areas - Python


Below is the code

# Import packages import cv2import numpy as np#Create MSER objectmser = cv2.MSER_create()#Your image path i-e receipt pathimg = cv2.imread('/home/rafiullah/PycharmProjects/python-ocr-master/receipts/73.jpg')#Convert to gray scalegray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)vis = img.copy()#detect regions in gray scale imageregions, _ = mser.detectRegions(gray)hulls = [cv2.convexHull(p.reshape(-1, 1, 2)) for p in regions]cv2.polylines(vis, hulls, 1, (0, 255, 0))cv2.imshow('img', vis)cv2.waitKey(0)mask = np.zeros((img.shape[0], img.shape[1], 1), dtype=np.uint8)for contour in hulls:    cv2.drawContours(mask, [contour], -1, (255, 255, 255), -1)#this is used to find only text regions, remaining are ignoredtext_only = cv2.bitwise_and(img, img, mask=mask)cv2.imshow("text only", text_only)cv2.waitKey(0)


This is an old post, yet I'd like to contribute that if you are trying to extract all the texts out of an image, here is the code to get that text in an array.

import cv2import numpy as npimport reimport pytesseractfrom pytesseract import image_to_stringpytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"from PIL import Imageimage_obj = Image.open("screenshot.png")rgb = cv2.imread('screenshot.png')small = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)#threshold the image_, bw = cv2.threshold(small, 0.0, 255.0, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)# get horizontal mask of large size since text are horizontal componentskernel = cv2.getStructuringElement(cv2.MORPH_RECT, (20, 1))connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)# find all the contourscontours, hierarchy,=cv2.findContours(connected.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)#Segment the text linescounter=0array_of_texts=[]for idx in range(len(contours)):    x, y, w, h = cv2.boundingRect(contours[idx])    cropped_image = image_obj.crop((x-10, y, x+w+10, y+h ))    str_store = re.sub(r'([^\s\w]|_)+', '', image_to_string(cropped_image))    array_of_texts.append(str_store)    counter+=1print(array_of_texts)