想检测拼图的边角部分,但找不到每块的4个角
Want to detect edge and corner parts in a jigsaw puzzle, but can't find the 4 corners of each piece
我有一个拼图游戏,想自动区分拼图中的 "normal"、"edge" 和 "corner" 个部分(我希望这些词的定义很明显任何玩过拼图游戏的人)
为了让事情更简单,我开始选择 9 个部分,其中 4 个是正常的,4 个是边,一个是角。原始图像如下所示:
我现在的第一个想法是检测每个单片的4个"major corners",然后进行如下操作:
- 如果两个相邻"major corners"之间的轮廓是一条直线就是一条边
- 三个相邻"major corners"之间的两条轮廓线是直线就是一个角
- 如果两个相邻"major corners"之间没有直线,则为正常部分。
但是,我在为每件作品提取四个 "major corners" 时遇到问题(我试图为此使用 Harris 角)
我的代码,包括一些预处理,附在下面,连同一些结果,包括我得到的哈里斯角。任何意见表示赞赏。
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image.png')
gray= cv2.imread('image.png',0)
# Threshold to detect rectangles independent from background illumination
ret2,th3 = cv2.threshold(gray,220,255,cv2.THRESH_BINARY_INV)
# Detect contours
_, contours, hierarchy = cv2.findContours( th3.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Draw contours
h, w = th3.shape[:2]
vis = np.zeros((h, w, 3), np.uint8)
cv2.drawContours( vis, contours, -1, (128,255,255), -1)
# Print Features of each contour and select some contours
contours2=[]
for i, cnt in enumerate(contours):
cnt=contours[i]
M = cv2.moments(cnt)
if M['m00'] != 0:
# for definition of features cf http://docs.opencv.org/3.1.0/d1/d32/tutorial_py_contour_properties.html#gsc.tab=0
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
area = cv2.contourArea(cnt)
x,y,w,h = cv2.boundingRect(cnt)
aspect_ratio = float(w)/h
rect_area = w*h
extent = float(area)/rect_area
print i, cx, cy, area, aspect_ratio, rect_area, extent
if area < 80 and area > 10:
contours2.append(cnt)
# Detect Harris corners
dst = cv2.cornerHarris(th3,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None, iterations=5)
# Threshold for an optimal value, it may vary depending on the image.
harris=img.copy()
print harris.shape
harris[dst>0.4*dst.max()]=[255,0,0]
titles = ['Original Image', 'Thresholding', 'Contours', "Harris corners"]
images = [img, th3, vis, harris]
for i in xrange(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
根据您获得的“等高线”图像(代码中的 vis
变量),我将图像拆分为每个 tile/image 仅获得 1 个拼图:
tiles = []
for i in range(len(contours)):
x, y, w, h = cv2.boundingRect(contours[i])
if w < 10 and h < 10:
continue
shape, tile = np.zeros(thresh.shape[:2]), np.zeros((300,300), 'uint8')
cv2.drawContours(shape, [contours[i]], -1, color=1, thickness=-1)
shape = (vis[:,:,1] * shape[:,:])[y:y+h, x:x+w]
tile[(300-h)//2:(300-h)//2+h , (300-w)//2:(300-w)//2+w] = shape
tiles.append(tile)
对于每个图块,我应用以下内容:
filter_median
控制边框的噪点
- 求最小外接圆的圆心
- 将棋子的轮廓转为基于圆心的极坐标,保留
rho
分量,得到一个图表,其中较高的值表示离中心较远的点。
- 消除粗糙边缘的平滑功能。对于 bottom-right 部分,我得到类似
的内容
- 通过分析函数找出“旋钮”和“孔”的数量。得到的旋钮数为4 - number of peaks/maxima(4个峰必然是片子的角,离中心越远),我发现“孔”的数量是valleys/minima 低于 50(这里可能需要一些不同的阈值或图像大小归一化才能使这项工作更普遍)。
- 知道特征的数量(“旋钮”+“孔”),就很容易得到作品的类型:
- 4个特点:中心件
- 3个特征:边框
- 2个特征:角片
我用以下方法做到这一点:
for image in tiles:
img = image.copy()
img = filters.median_filter(img.astype('uint8'), size=15)
plt.imshow(img)
plt.show()
contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
(center_x, center_y), _ = cv2.minEnclosingCircle(contours[0])
# get contour points in polar coordinates
rhos = []
for i in range(len(contours[0])):
x, y = contours[0][i][0]
rho, _ = cart2pol(x - center_x, y - center_y)
rhos.append(rho)
rhos = smooth(rhos, 7) # adjust the smoothing amount if necessary
# compute number of "knobs"
n_knobs = len(find_peaks(rhos, height=0)[0]) - 4
# adjust those cases where the peak is at the borders
if rhos[-1] >= rhos[-2] and rhos[0] >= rhos[1]:
n_knobs += 1
# compute number of "holes"
rhos[rhos >= 50] = rhos.max()
rhos = 0 - rhos + abs(rhos.min())
n_holes = len(find_peaks(rhos)[0])
print(f"knobs: {n_knobs}, holes: {n_holes}")
# classify piece
n_features = n_knobs + n_holes
if n_features > 4 or n_features < 0:
print("ERROR")
if n_features == 4:
print("Central piece")
if n_features == 3:
print("Border piece")
if n_features == 2:
print("Corner piece")
我有一个拼图游戏,想自动区分拼图中的 "normal"、"edge" 和 "corner" 个部分(我希望这些词的定义很明显任何玩过拼图游戏的人)
为了让事情更简单,我开始选择 9 个部分,其中 4 个是正常的,4 个是边,一个是角。原始图像如下所示:
我现在的第一个想法是检测每个单片的4个"major corners",然后进行如下操作:
- 如果两个相邻"major corners"之间的轮廓是一条直线就是一条边
- 三个相邻"major corners"之间的两条轮廓线是直线就是一个角
- 如果两个相邻"major corners"之间没有直线,则为正常部分。
但是,我在为每件作品提取四个 "major corners" 时遇到问题(我试图为此使用 Harris 角)
我的代码,包括一些预处理,附在下面,连同一些结果,包括我得到的哈里斯角。任何意见表示赞赏。
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('image.png')
gray= cv2.imread('image.png',0)
# Threshold to detect rectangles independent from background illumination
ret2,th3 = cv2.threshold(gray,220,255,cv2.THRESH_BINARY_INV)
# Detect contours
_, contours, hierarchy = cv2.findContours( th3.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Draw contours
h, w = th3.shape[:2]
vis = np.zeros((h, w, 3), np.uint8)
cv2.drawContours( vis, contours, -1, (128,255,255), -1)
# Print Features of each contour and select some contours
contours2=[]
for i, cnt in enumerate(contours):
cnt=contours[i]
M = cv2.moments(cnt)
if M['m00'] != 0:
# for definition of features cf http://docs.opencv.org/3.1.0/d1/d32/tutorial_py_contour_properties.html#gsc.tab=0
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
area = cv2.contourArea(cnt)
x,y,w,h = cv2.boundingRect(cnt)
aspect_ratio = float(w)/h
rect_area = w*h
extent = float(area)/rect_area
print i, cx, cy, area, aspect_ratio, rect_area, extent
if area < 80 and area > 10:
contours2.append(cnt)
# Detect Harris corners
dst = cv2.cornerHarris(th3,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None, iterations=5)
# Threshold for an optimal value, it may vary depending on the image.
harris=img.copy()
print harris.shape
harris[dst>0.4*dst.max()]=[255,0,0]
titles = ['Original Image', 'Thresholding', 'Contours', "Harris corners"]
images = [img, th3, vis, harris]
for i in xrange(4):
plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()
根据您获得的“等高线”图像(代码中的 vis
变量),我将图像拆分为每个 tile/image 仅获得 1 个拼图:
tiles = []
for i in range(len(contours)):
x, y, w, h = cv2.boundingRect(contours[i])
if w < 10 and h < 10:
continue
shape, tile = np.zeros(thresh.shape[:2]), np.zeros((300,300), 'uint8')
cv2.drawContours(shape, [contours[i]], -1, color=1, thickness=-1)
shape = (vis[:,:,1] * shape[:,:])[y:y+h, x:x+w]
tile[(300-h)//2:(300-h)//2+h , (300-w)//2:(300-w)//2+w] = shape
tiles.append(tile)
对于每个图块,我应用以下内容:
filter_median
控制边框的噪点- 求最小外接圆的圆心
- 将棋子的轮廓转为基于圆心的极坐标,保留
rho
分量,得到一个图表,其中较高的值表示离中心较远的点。 - 消除粗糙边缘的平滑功能。对于 bottom-right 部分,我得到类似
- 通过分析函数找出“旋钮”和“孔”的数量。得到的旋钮数为4 - number of peaks/maxima(4个峰必然是片子的角,离中心越远),我发现“孔”的数量是valleys/minima 低于 50(这里可能需要一些不同的阈值或图像大小归一化才能使这项工作更普遍)。
- 知道特征的数量(“旋钮”+“孔”),就很容易得到作品的类型:
- 4个特点:中心件
- 3个特征:边框
- 2个特征:角片
我用以下方法做到这一点:
for image in tiles:
img = image.copy()
img = filters.median_filter(img.astype('uint8'), size=15)
plt.imshow(img)
plt.show()
contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
(center_x, center_y), _ = cv2.minEnclosingCircle(contours[0])
# get contour points in polar coordinates
rhos = []
for i in range(len(contours[0])):
x, y = contours[0][i][0]
rho, _ = cart2pol(x - center_x, y - center_y)
rhos.append(rho)
rhos = smooth(rhos, 7) # adjust the smoothing amount if necessary
# compute number of "knobs"
n_knobs = len(find_peaks(rhos, height=0)[0]) - 4
# adjust those cases where the peak is at the borders
if rhos[-1] >= rhos[-2] and rhos[0] >= rhos[1]:
n_knobs += 1
# compute number of "holes"
rhos[rhos >= 50] = rhos.max()
rhos = 0 - rhos + abs(rhos.min())
n_holes = len(find_peaks(rhos)[0])
print(f"knobs: {n_knobs}, holes: {n_holes}")
# classify piece
n_features = n_knobs + n_holes
if n_features > 4 or n_features < 0:
print("ERROR")
if n_features == 4:
print("Central piece")
if n_features == 3:
print("Border piece")
if n_features == 2:
print("Corner piece")