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

问题描述 投票:1回答:1

我想检测并隔离图像中所有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

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

python image opencv image-processing edge-detection
1个回答
0
投票

这是一个简单的方法

  • 将图像转换为灰度和高斯模糊
  • 自适应阈值
  • 膨胀以形成单个轮廓
  • 使用宽高比和轮廓区域查找轮廓和过滤器
  • 使用Numpy切片提取ROI并保存ROI

检测到的对象

enter image description here

这里是每个单独保存的投资回报率

enter image description here

代码

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()
© www.soinside.com 2019 - 2024. All rights reserved.