简体   繁体   English

Opencv Python:如何检测图片上的填充矩形

[英]Opencv Python: How to detect filled, rectangular shapes on picture

I have the picture below.我有下面的图片。 I want to find the the black colored rectangles on the left using opencv.我想使用 opencv 找到左侧的黑色矩形。 Thanks for help=)谢谢你的帮助=) 在此处输入图像描述

Here's a simple approach using thresholding + morphological operations.这是使用阈值+形态学操作的简单方法

  1. Obtain binary image.获取二值图像。 Load image, convert to grayscale, then adaptive threshold加载图像,转换为灰度,然后自适应阈值

  2. Fill rectangular contours.填充矩形轮廓。 Find contours and fill the contours to create filled rectangular blocks.查找轮廓并填充轮廓以创建填充的矩形块。

  3. Perform morph open.执行变形打开。 We create a rectangular structuring element and morph open to remove the lines我们创建一个矩形结构元素并变形打开以删除线条

  4. Draw rectangles around largest rectangles Find contours and draw bounding rectangles around rectangles with an area above a certain treshold.在最大矩形周围绘制矩形查找轮廓并在矩形周围绘制边界矩形,其面积高于某个阈值。


Here's each step visualized:这是每个步骤的可视化:

Obtain binary image获取二值图像

在此处输入图像描述

Adaptive treshold自适应阈值

在此处输入图像描述

Filled rectangular contours填充矩形轮廓

在此处输入图像描述

Perform morph open执行变形打开

在此处输入图像描述

Draw rectangles around largest rectangles在最大的矩形周围绘制矩形

在此处输入图像描述

In code:在代码中:

import numpy as np 
import cv2

#load the image
image = cv2.imread("mtF6y.jpg")

# grayscale
result = image.copy()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

# adaptive threshold
thresh = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,51,9)

# Fill rectangular contours
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:
    cv2.drawContours(thresh, [c], -1, (255,255,255), -1)

# Morph open
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9,9))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=4)

# Draw rectangles, the 'area_treshold' value was determined empirically
cnts = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
area_treshold = 4000
for c in cnts:
    if cv2.contourArea(c) > area_treshold :
      x,y,w,h = cv2.boundingRect(c)
      cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 3)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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