写一段python程序实现基于opencv识别PCB板上的蓝膜针点是否扎的合理,在针孔60%面积范围内即为合理
时间: 2024-03-23 10:41:27 浏览: 94
好的,我可以帮你编写一段基于OpenCV的Python程序来实现PCB板上蓝膜针点的自动识别。以下是程序的主要步骤:
1. 导入必要的库和模块:
```python
import cv2
import numpy as np
```
2. 读取图像并进行预处理:
```python
img = cv2.imread('pcb.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
```
3. 提取图像中的蓝色区域:
```python
lower_blue = np.array([100, 50, 50])
upper_blue = np.array([130, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
```
4. 对提取出来的蓝色区域进行形态学处理,以便更好地检测针点:
```python
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
```
5. 通过轮廓检测找到针点,并计算针孔面积占比:
```python
contours, hierarchy = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
area = cv2.contourArea(c)
(x, y, w, h) = cv2.boundingRect(c)
aspect_ratio = w / float(h)
if aspect_ratio >= 0.5 and aspect_ratio <= 2.0 and area > 20:
cv2.drawContours(img, [c], -1, (0, 255, 0), 2)
percent = float(area) / float(w * h)
if percent >= 0.6:
print('针点合理')
else:
print('针点不合理')
```
完整的程序如下:
```python
import cv2
import numpy as np
img = cv2.imread('pcb.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([100, 50, 50])
upper_blue = np.array([130, 255, 255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
contours, hierarchy = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
area = cv2.contourArea(c)
(x, y, w, h) = cv2.boundingRect(c)
aspect_ratio = w / float(h)
if aspect_ratio >= 0.5 and aspect_ratio <= 2.0 and area > 20:
cv2.drawContours(img, [c], -1, (0, 255, 0), 2)
percent = float(area) / float(w * h)
if percent >= 0.6:
print('针点合理')
else:
print('针点不合理')
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
你可以将程序中的`pcb.jpg`替换成你自己的PCB板图像,然后运行程序即可得到针点是否合理的结果。
阅读全文