Tutorial

Table Of Contents
104
Convert the picture to black and white, and then binarize (the value of each pixel in the picture is 255
except 0)
'''
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
retval, img = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)
img = cv2.erode(img, None, iterations=6) #Use Corrosion Denoising
colorPos = img[linePos] #Get an array of pixel values for linePos
try:
lineColorCount_Pos = np.sum(colorPos == lineColorSet) #Get the number of pixels of line color
(line width)
lineIndex_Pos = np.where(colorPos == lineColorSet) #Get the horizontal position of the end
point of the line in the linePos line
'''
Use the endpoint position and line width to calculate the position of the center point of the line
'''
left_Pos = lineIndex_Pos[0][lineColorCount_Pos-1]
right_Pos = lineIndex_Pos[0][0]
center_Pos = int((left_Pos+right_Pos)/2)
print('The position of the center point of the line is%d'%center_Pos)
except:
'''
If no line is detected, the line width above 0 will cause an error, so that you know that no line has
been detected
'''
center_Pos = 0
print('No line detected')
'''
Draw a horizontal reference line
'''
cv2.line(img,(0,linePos),(640,linePos),(255,255,64),1)
if center_Pos:
'''
If a line is detected, draw the center point of the line
'''
cv2.line(img,(center_Pos,linePos+300),(center_Pos,linePos-300),(255,255,64),1)
# encode as a jpeg image and return it
yield cv2.imencode('.jpg', img)[1].tobytes()