gpt4 book ai didi

python - 想检测拼图的边角部分,但找不到每 block 的4个角

转载 作者:行者123 更新时间:2023-12-05 06:42:32 25 4
gpt4 key购买 nike

我有一个拼图游戏,想要自动区分拼图中的“正常”、“边缘”和“角”部分(我希望那些玩过拼图游戏的人都清楚这些词的定义)

为了让事情更简单,我开始选择 9 个部分,其中 4 个是正常的,4 个是边,一个是角。原始图像如下所示: enter image description here

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

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

但是,我在为每件作品提取四个“主要角”时遇到问题(我试图为此使用 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()

enter image description here

最佳答案

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

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

  1. filter_median 控制边界噪声
  2. 找到最小外接圆的圆心
  3. 将零件的轮廓转换为基于圆心的极坐标,同时保留 rho 分量,从而生成一个图表,其中较高的值表示离中心较远的点。
  4. 平滑函数以去除粗糙的边缘。对于右下角的部分,我得到类似 distance from center graph 的内容
  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")

关于python - 想检测拼图的边角部分,但找不到每 block 的4个角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com