练习数火柴数量¶
import cv2
import numpy as np
# 读取图像
image = cv2.imread('smoke_detect.jpg')
# 转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 使用高斯滤波去除噪声
gaussian = cv2.GaussianBlur(gray, (5, 5), 0)
# 边缘检测
edges = cv2.Canny(gaussian, 50, 150)
# 查找轮廓
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
# 计算轮廓的边界框
x, y, w, h = cv2.boundingRect(contour)
# 筛选合适的轮廓,例如面积大小等
if cv2.contourArea(contour) > 500:
# 在原图上绘制轮廓
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Smoke Detected', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
In [1]:
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
def show(img):
# 判断图片的维度
img = img.astype(np.uint8)
if img.ndim == 2: # 说明是灰度图读取
plt.imshow(img, cmap='gray')
elif img.ndim == 3: # 彩色图片
img2 = cv.cvtColor(img, cv.COLOR_BGR2RGB)
plt.imshow(img2)
else:
print('不知道是什么图!')
return
plt.show()
In [2]:
import cv2
import numpy as np
# 读取图像
image = cv2.imread("../pic/chuanchuan_detect.png")
# 预处理:灰度化
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gaussian = cv2.GaussianBlur(gray, (5, 5), 0)
# 边缘检测
edges = cv2.Canny(gaussian, 60, 120)
# 霍夫圆变换
circles = cv2.HoughCircles(edges, cv2.HOUGH_GRADIENT, dp=25, minDist=1, param1=1, param2=20, minRadius=5, maxRadius=30)
# 钢管计数
steel_pipe_count = 0
# 绘制检测到的钢管
if circles is not None:
circles = np.round(circles[0, :]).astype(int)
for (x, y, r) in circles:
cv2.circle(image, (x, y), r, (0, 255, 0), 2)
cv2.circle(image, (x, y), 2, (0, 0, 255), 3)
steel_pipe_count += 1
show(image)
# 输出钢管数量
print("Steel Pipe Count:", steel_pipe_count)
Steel Pipe Count: 64
In [ ]: