如何找到图像中的所有矩形图块?

How to find all rectangular shaped tiles in an image?

我想检测并隔离(获取子图像)图像中的所有 Rummikub 图块。这是 Rummikub 瓷砖的图像:

我试图在边缘图像中找到图块的轮廓。但是,我无法找到所有瓷砖的所有轮廓。

这是我目前得到的:

import matplotlib.pyplot as plt
from skimage.color import rgb2gray
import cv2
import imutils
from imutils import contours

# Load image
img = cv2.imread('RK1.jpg',3)

# Converting the image to grayscale.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Smoothing without removing edges.
gray_filtered = cv2.bilateralFilter(gray, 6, 400, 400)

# Applying the canny filter
edges_filtered = cv2.Canny(gray_filtered, 50, 30)

# find contours in the edged image
contours= cv2.findContours(edges_filtered, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)

# loop over our contours
for contour in contours:
    # approximate the contour
    peri = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.015 * peri, True)

    # if our approximated contour has four points, then draw contour
    if len(approx) == 4:
        cv2.drawContours(img, [approx], -1, (0, 255, 0), 3)

这是结果:

Result of rectangle detection

我非常感谢有关如何可靠地找到所有图块的所有轮廓的建议。

这是一个简单的方法

  • 将图像转换为灰度和高斯模糊
  • 自适应阈值
  • 扩张形成单个轮廓
  • 使用纵横比和轮廓面积查找轮廓并进行过滤
  • 使用 Numpy 切片提取 ROI 并保存 ROI

检测到对象

这是每个单独保存的 ROI

代码

import cv2

image = cv2.imread('1.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.adaptiveThreshold(blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,9,3)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
dilate = cv2.dilate(thresh, kernel, iterations=1)

cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

ROI_number = 0
for c in cnts:
    area = cv2.contourArea(c)
    peri = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.05 * peri, True)
    if len(approx) == 4 and area > 1000:
        x,y,w,h = cv2.boundingRect(approx)
        ROI = image[y:y+h, x:x+w]
        cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)
        ROI_number += 1

cv2.imshow('thresh', thresh)
cv2.imshow('dilate', dilate)
cv2.waitKey()