我有一个图像,其中包含一些手写的米值,我想找到字母m的位置,所以我可以裁剪它并只留下数字。
这是一个例子:
原始图片:输入图片如下所示,实际上这是我能得到的最好的手写输入,通常情况会更糟。
训练图像:我有一个m字母的列表,从我手写的不同图像中剪下来。
结果图片:我想要的结果
我已经尝试过使用opencv模板匹配功能,但它没有工作,也发现了这个github,但它也使用了模板匹配。 我想知道是否还有其他方法可以解决这个问题。
答案 0 :(得分:3)
似乎这封信总是在数字的末尾。如果这是真的,您可以采用更简单的方法:
Python 2.7和OpenCV 2.4的源代码:
import cv2
### load input image and convert it to grayscale
img = cv2.imread("input.png")
print("img shape=", img.shape)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#### extract all contours
_, contours, _ = cv2.findContours(gray.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# debug: draw all contours
#cv2.drawContours(img, contours, -1, (0, 0, 255), 2)
#cv2.imwrite("all_contours.jpg", img)
#### create one bounding box for every contour found
bb_list = []
for c in contours:
bb = cv2.boundingRect(c)
# save all boxes except the one that has the exact dimensions of the image (x, y, width, height)
if (bb[0] == 0 and bb[1] == 0 and bb[2] == img.shape[1] and bb[3] == img.shape[0]):
continue
bb_list.append(bb)
# debug: draw boxes
#img_boxes = img.copy()
#for bb in bb_list:
# x,y,w,h = bb
# cv2.rectangle(img_boxes, (x, y), (x+w, y+h), (0, 0, 255), 2)
#cv2.imwrite("boxes.jpg", img_boxes)
#### sort bounding boxes by the X value: first item is the left-most box
bb_list.sort(key=lambda x:x[0])
# debug: draw the last box of the list (letter M)
#print("letter M @ ", bb_list[-1])
#x,y,w,h = bb_list[-1]
#cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
#cv2.imwrite("last_contour.jpg", img)
### remove the last item from the list, i.e. remove box for letter M
bb_list = bb_list[:-1]
### and now the fun part: create one large bounding box to rule them all
x_start, _, _, _ = bb_list[0]
x_end, _, w_end, _ = bb_list[-1]
x = x_start
w = (x_end + w_end) - x_start
bb_list.sort(key=lambda y:y[1]) # sort by Y value: the first item has the smallest Y value
_, y, _, _ = bb_list[0]
bb_list.sort(key=lambda y:y[3]) # sort by Height value: the last item has the largest Height value
_, _, _, h = bb_list[-1]
print("x=", x, "y=", y, "w=", w, "h=", h)
# debug: draw the final region of interest
roi_img = img.copy()
cv2.rectangle(roi_img, (x, y), (x+w, y+h), (0, 0, 255), 2)
cv2.imwrite("roi.jpg", roi_img)
# crop to the roi
crop_img = img[y:y+h, x:x+w]
cv2.imwrite("crop.jpg", crop_img)
答案 1 :(得分:0)
如何计算连续点集,并删除最后一个"到右边"在图像的坐标?那将摆脱m字母
通常,read this to get the idea behind : Connected-component labeling
与像素相关的连接组件上的Python相关post on SO