Image Processing #12 - Detecting the center of text or curved line
There are times when you need information about the center line of text or curved parts of an image.
I'm making a drawing robot these days. After the robot drew the picture, I needed this method to sign it. If the center line pixel location information of the signature image is grasped, the robot can naturally sign by drawing a pen while passing through these pixels.
Even when developing an autonomous driving robot, in order not to deviate from the road designated by the robot, it may be possible to identify the center line of the road and move it around this line.
Implementing this function in OpenCV is quite simple.
opencv-contrib-python not opencv-python
There is one thing to note. It is recommended to install opencv-contrib-python instead of opencv-python, which is normally installed to use OpenCV in Python. In this example, a function called cv2.ximgproc.thinning is used, but ximgproc is not supported by opencv-python. opencv-contrib-python is installed with additional modules along with opencv-python. This additional module contains ximgproc.
If you have already installed opencv-python using pip or pip3, uninstall it and install opencv-contrib-python.
Note: Do not install both versions at the same time.
pip3 uninstall opencv-python pip3 install opencv-contrib-python
Execute the following code.
import cv2 import sys def detect(image): # some preprocessing thin = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) thin = cv2.blur(thin, (10, 10)) _, thin = cv2.threshold(thin, 220, 255, 0) # thin image to find clear contours thin = cv2.ximgproc.thinning(thin, thinningType=cv2.ximgproc.THINNING_GUOHALL) cv2.imshow("thin", thin) # dind contours # cnts, _ = cv2.findContours(thin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) cnts, _ = cv2.findContours(thin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # cnts, _ = cv2.findContours(thin, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for cnt in cnts: cv2.drawContours(image, [cnt], 0, (255, 0, 0), 3) # blue return image image = cv2.imread("C:\\lsh\\study\\opencv\\halo.jpg") if image is None: print('No image') sys.exit() output = detect(image) cv2.imshow("CenterLine", output) cv2.waitKey(0) cv2.destroyAllWindows()
You will see the following window.
If you want to check in cantour units, you can draw a rectangle surrounding the cantour. Just add the following 2 lines to the code that draws the center line.
for cnt in cnts: cv2.drawContours(image, [cnt], 0, (255, 0, 0), 3) # blue [x,y,w,h] = cv2.boundingRect(cnt) cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)
You will see the following window.
댓글
댓글 쓰기