先感谢大佬(文章引用):https://blog.csdn.net/qq_33854260/article/details/106297999
这是一个关于预制构件的项目,已经研究好久了 今天把这些贴上来
需要处理的原图片长这个样子:
简单介绍一下,这个东西叫做叠合板,是现在国家大力推广的装配式建筑里面的一种常用构件,我们需要识别检测的就是它的尺寸。即获得像素块即可,因为相机是固定的直接根据实际长度算出来一个比例尺就好了。最主要的是先搞定图像的处理。
首先对他进行一个灰度图,二值化的处理,二值化是自动计算阈值的二值化。先看这部分实现的代码:
import cv2
import numpy as np
from matplotlib import pyplot as plt
image=cv2.imread('00000008.jpg') #图片就在当前目录下
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) #把输入图像灰度化
h, w =gray.shape[:2]
m = np.reshape(gray, [1,w*h])
mean = m.sum()/(w*h)
ret, mask_sel = cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY)
#, contours, hierarchy = cv2.findContours(mask_sel,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contours,hierarchy = cv2.findContours(mask_sel,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
#找到最大区域并填充
#print("contours:",contours)
cv2.namedWindow("mask_sel", cv2.WINDOW_NORMAL)
cv2.imshow("mask_sel", mask_sel)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出的是这样的一个图片:
接下来需要对二值化的图形进行一个求最大连通区域的操作。先省略。因为觉得影响不大。
直接对二值化的图片进行矩形识别。结果识别不出来,还是连通吧
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 00:31:26 2020
@author: 江湖夜雨十年灯
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
image=cv2.imread('00000008.jpg') #图片就在当前目录下
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) #把输入图像灰度化
h, w =gray.shape[:2]
m = np.reshape(gray, [1,w*h])
mean = m.sum()/(w*h)
ret, mask_sel = cv2.threshold(gray, mean, 255, cv2.THRESH_BINARY)
#, contours, hierarchy = cv2.findContours(mask_sel,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
contours,hierarchy = cv2.findContours(mask_sel,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
area = []
for j in range(len(contours)): #找到最大区域并填充
area.append(cv2.contourArea(contours[j]))
max_idx = np.argmax(area)
max_area = cv2.contourArea(contours[max_idx])
for k in range(len(contours)):
if k != max_idx:
cv2.fillPoly(mask_sel, [contours[k]], 0) #找到最大区域并填充
cv2.drawContours(image, contours, -2, (0,255,0), 12)
cv2.drawContours(mask_sel, contours, -2, (0,255,0), 12)
cnt = contours[np.argmax([cv2.contourArea(cnt) for cnt in contours])]
#找到最大区域并填充
#print("contours:",contours)
cv2.namedWindow("mask_sel", cv2.WINDOW_NORMAL)
cv2.imshow("mask_sel", mask_sel)
#cv2.imshow("mask_se2l", hierarchy)
cv2.waitKey(0)
cv2.destroyAllWindows()
是这样一个效果,叠合板这种东西和那些流水线的零件还不一样,现场条件太差。
下次接着写