我是图像处理的新手,我需要将图像文件中的纵横字词网格转换为相应的二进制等价,即输出应该是黑色方块为1,白色方块为0的数组。另外,图像中的所有其他无关信息,如文本等,都将被忽略,只对网格进行数字化。
角点检测算法能否帮助我们检测纵横字谜的角点,然后使用蛮力相应地数字化像素块?这是最好的方法吗?或者有什么有效的方法来完成这项任务?我更喜欢基于python的解决方案。
发布于 2013-06-07 13:20:35
我认为你不需要在这里使用角点检测。只要使用轮廓本身,你就可以解决它(如果你的图像是这些直接的)。下面是打印上图数组的代码。代码注释如下:
import numpy as np
import cv2
img = cv2.imread('cross.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
thresh2 = cv2.bitwise_not(thresh)
contours,hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, 1)
max_area = -1
# find contours with maximum area
for cnt in contours:
approx = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt,True), True)
if len(approx) == 4:
if cv2.contourArea(cnt) > max_area:
max_area = cv2.contourArea(cnt)
max_cnt = cnt
max_approx = approx
# cut the crossword region, and resize it to a standard size of 130x130
x,y,w,h = cv2.boundingRect(max_cnt)
cross_rect = thresh2[y:y+h, x:x+w]
cross_rect = cv2.resize(cross_rect,(130,130))
# you need to uncomment these lines if your image is rotated
#new_pts = np.float32([[0,0], [0,129],[129,129],[129,0]])
#old_pts = max_approx.reshape(4,2).astype('float32')
#M = cv2.getPerspectiveTransform(old_pts,new_pts)
#cross_rect = cv2.warpPerspective(thresh2,M,(130,130))
cross = np.zeros((13,13))
# select each box, if number of white pixels is more than 50, it is white box
for i in xrange(13):
for j in xrange(13):
box = cross_rect[i*10:(i+1)*10, j*10:(j+1)*10]
if cv2.countNonZero(box) > 50:
cross.itemset((i,j),1)
print cross
我得到了上图的如下输出:
[[ 0. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 0. 1. 0. 1. 0. 1. 0. 0. 0. 1. 0. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1.]
[ 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1.]
[ 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 0. 0. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1.]
[ 1. 1. 1. 1. 0. 0. 0. 0. 0. 1. 1. 1. 1.]
[ 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 0. 0. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1.]
[ 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1. 0. 1.]
[ 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 1. 1.]
[ 1. 0. 1. 0. 0. 0. 1. 0. 1. 0. 1. 0. 1.]
[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 0.]]
我已经写了一个代码,从图像中提取数独细节,详细解释在以下链接(教程是不完整的)。您可以参考它们了解更多详细信息:
http://opencvpython.blogspot.com/2012/06/sudoku-solver-part-1.html
http://opencvpython.blogspot.com/2012/06/sudoku-solver-part-2.html
http://opencvpython.blogspot.com/2012/06/some-common-questions.html
发布于 2013-06-07 11:33:22
角点检测可能会在文本上找到角点等--你必须尝试一下。
我将从使用霍夫变换http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/hough_lines/hough_lines.html查找行开始。一旦你检测到所有的直线,你就可以通过找到直线的交点来找到正方形的角点。一旦知道了正方形的位置,就可以很容易地确定正方形是黑色还是白色。
您还可以编写Hough变换来检测矩形,但这可能是不必要的复杂操作。
不管你是用Python,C++,还是Java都没有多大区别。
https://stackoverflow.com/questions/16975556
复制相似问题