Square detection in image

后端 未结 2 1839
-上瘾入骨i
-上瘾入骨i 2021-02-13 15:31

I am trying to detect all the squared shaped dice images so that i can crop them individually and use that for OCR. Below is the Original image:

Here is the co

相关标签:
2条回答
  • 2021-02-13 15:45

    That extra piece of information is absolutely golden. Yes, given the 5x5 matrix of dice, you can nail the positions quite well. The dice you can identify give you the center, size, and orientation of the dice. Simply continue those patterns along both axes. For your second pass, increase the contrast in each "region of interest" where you expect to find the edge of a douse (never say die!). You know within a few pixels where the edges will be: simply attenuate the image until you identify those edges.

    0 讨论(0)
  • 2021-02-13 15:46

    Here's an approach

    • Convert image to grayscale and median blur to smooth image
    • Sharpen image to enhance edges
    • Threshold
    • Perform morphological transformations
    • Find contours and filter using minimum/maximum threshold area
    • Crop and save ROI

    Sharpen image with cv2.filter2D(). We use a generic sharpen kernel, other kernels can be found here

    Now threshold to get a binary image

    Perform morphological operations

    From here we find contours and filter using cv2.contourArea() with minimum/maximum threshold areas.

    We can crop each desired square region using Numpy slicing and save each ROI like this

    x,y,w,h = cv2.boundingRect(c)
    ROI = image[y:y+h, x:x+h]
    cv2.imwrite('ROI_{}.png'.format(image_number), ROI)
    

    import cv2
    import numpy as np
    
    image = cv2.imread('1.png')
    
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.medianBlur(gray, 5)
    sharpen_kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
    sharpen = cv2.filter2D(blur, -1, sharpen_kernel)
    
    thresh = cv2.threshold(sharpen,160,255, cv2.THRESH_BINARY_INV)[1]
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
    close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)
    
    cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    
    min_area = 100
    max_area = 1500
    image_number = 0
    for c in cnts:
        area = cv2.contourArea(c)
        if area > min_area and area < max_area:
            x,y,w,h = cv2.boundingRect(c)
            ROI = image[y:y+h, x:x+h]
            cv2.imwrite('ROI_{}.png'.format(image_number), ROI)
            cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)
            image_number += 1
    
    cv2.imshow('sharpen', sharpen)
    cv2.imshow('close', close)
    cv2.imshow('thresh', thresh)
    cv2.imshow('image', image)
    cv2.waitKey()
    
    0 讨论(0)
提交回复
热议问题