python - Opencv Python:如何检测图片上的填充矩形
解决方案
这是使用阈值+形态学操作的简单方法。
获取二值图像。加载图像,转换为灰度,然后自适应阈值
填充矩形轮廓。查找轮廓并填充轮廓以创建填充的矩形块。
执行变形打开。我们创建一个矩形结构元素并变形打开以删除线条
在最大矩形周围绘制矩形查找轮廓并在矩形周围绘制边界矩形,其面积高于某个阈值。
这是每个步骤的可视化:
获取二值图像
自适应阈值
填充矩形轮廓
执行变形打开
在最大的矩形周围绘制矩形
在代码中:
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()
推荐阅读
- sql - postgres 函数未正确执行
- javascript - 错误的表情符号显示
- python - Python HTTP套接字:并不总是从发送JSON的客户端接收所有内容
- reactjs - 如何在函数 App() 父级和 Material-UI 嵌套侧边栏子级之间传递数据
- algorithm - 通过删除传递节点来减少图
- c# - 如何迁移实体框架中已经建立的一对多关系?
- javascript - 将经纬度坐标转换为 NMEA (DDDMM.MM)
- excel - 根据另一个单元格的值显示值
- javascript - Javascript:TypeError:回调不是函数
- azure-iot-hub - 查询设备孪生阵列属性