3

我有一个拼图游戏,想自动区分该拼图中的“正常”、“边缘”和“角”块(我希望这些词的定义对于曾经玩过拼图游戏的人来说是显而易见的)

为了使事情更容易,我从 9 个部分开始,其中 4 个是正常的,4 个是边缘,一个是角。原始图像如下所示: 在此处输入图像描述

我现在的第一个想法是检测每个单件的 4 个“主要角”,然后进行如下操作:

  • 如果两个相邻“主要角”之间的轮廓是一条直线,则它是一条边
  • 如果三个相邻“主要角”之间的两个轮廓是直线,则它是一个角
  • 如果两个相邻的“主要角”之间没有直线,这是正常的部分。

但是,我在为每件作品提取四个“主要角”时遇到问题(我试图为此使用哈里斯角)

我的代码,包括一些预处理,附在下面,连同一些结果,包括我得到的哈里斯角。任何输入表示赞赏。

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()

在此处输入图像描述

4

1 回答 1

1

从您得到的“轮廓”图像(vis代码中的变量)中,我将图像拆分为每个图块/图像仅获得 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)

对于每个图块,我应用以下内容:

  1. filter_median控制边界的噪音
  2. 找到最小封闭圆的中心
  3. 将工件的轮廓转换为基于圆心的极坐标,保留rho分量,从而得到一个图形,其中较高的值表示离中心较远的点。
  4. 平滑功能以消除粗糙边缘。对于右下角的部分,我得到类似到中心图的距离
  5. 通过分析函数找到“旋钮”和“孔”的数量。旋钮的数量获得为 4 - 峰数/最大值(4 个峰不可避免地是一块角,离中心更远),我发现“孔”的数量是谷数/最小值低于 50(这里可能需要一些不同的阈值或图像大小标准化以使这项工作更普遍)。
  6. 知道特征的数量(“旋钮”+“孔”),很容易得到片的类型:
    • 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")
于 2022-02-20T20:33:29.760 回答