简体   繁体   中英

Identify table grid in image

I have to identify the table grid in this image and change it to Grimson red color. I am a beginner in image processing.

img_arr = mpimg.imread("1.jpg")

plt.imshow(img_arr)

grid = img_arr[470:800,42:670,(0,1,2)]

plt.imshow(grid.data)

Based on the image dimensions I was able to see the grid part of the image but I don't have idea how to identify the grid and change its color. If anyone has any idea about this, please reply.

Here's an approach:

  • Convert image to grayscale and threshold
  • Find contours and filter using contour area to isolate the grid
  • Find horizontal and vertical lines
  • Draw lines onto image

Here's the result

import cv2
import numpy as np

image = cv2.imread('1.png')
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Detect only grid
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    area = cv2.contourArea(c)
    if area > 10000:
        cv2.drawContours(mask, [c], -1, (255,255,255), -1)

mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
mask = cv2.bitwise_and(mask, thresh)

# Find horizontal lines
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (55,1))
detect_horizontal = cv2.morphologyEx(mask, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
cnts = cv2.findContours(detect_horizontal, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (0,0,255), 2)

# Find vertical lines
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,25))
detect_vertical = cv2.morphologyEx(mask, cv2.MORPH_OPEN, vertical_kernel, iterations=2)
cnts = cv2.findContours(detect_vertical, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    cv2.drawContours(image, [c], -1, (0,0,255), 2)

cv2.imshow('thresh', thresh)
cv2.imshow('mask', mask)
cv2.imshow('image', image)
cv2.waitKey()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM