我有一个像这样的灯泡图像:
我想提取上面写的数字:
然后传给ocr.
如何使用 OpenCV 执行此操作?
我写过这样的代码,但它对ocr不好。
def img_process(frame):
original_frame = frame.copy()
rected = frame.copy()
add_rect(rected)
croped = crop(frame)
frame_grey = cv2.cvtColor(croped, cv2.COLOR_BGR2GRAY)
thr = cv2.adaptiveThreshold(frame_grey.copy(), 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 13, 8)
final = remove_lines(thr)
final = cv2.morphologyEx(final, cv2.MORPH_CLOSE, np.ones((2, 2)))
cnts, hiercachy = cv2.findContours(final, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sorted_contours= sorted(cnts, key=cv2.contourArea, reverse= True)
if len(sorted_contours) > 0:
largest_item= sorted_contours[0]
x, y, w, h = cv2.boundingRect(largest_item)
cv2.rectangle(final, (x, y), (x+w, y+h), (255, 0,0), 2)
return rected, final
def remove_lines(img_thr):
# Remove horizontal
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 3))
detected_lines = cv2.morphologyEx(img_thr, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
cv2.drawContours(img_thr, \[c\], -1, (0, 0, 0), -1)
# Remove vertical
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 10))
detected_lines = cv2.morphologyEx(img_thr, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detected_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts\[0\] if len(cnts) == 2 else cnts\[1\]
for c in cnts:
cv2.drawContours(img_thr, \[c\], -1, (0, 0, 0), -1)
return img_thr
带有矩形的原始图像,用于在代码上定位相机:
裁剪和处理的图像: