import cv2 as cv
import numpy as np
# 读取图像(请将此处的图像路径替换为你实际的图像路径)
img = cv.imread('test.jpg')
# 1. 使用3x3的高斯滤波器对图像滤波,去除图像中的高斯噪声
kernel_size = (3, 3)
sigma = 0 # 可以根据实际情况调整标准差,这里设为0默认根据核大小计算合适的值
blurred = cv.GaussianBlur(img, kernel_size, sigma)
# 2. 灰度化滤波处理过后的图像,赋值给变量gray
gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
# 3. 使用cv.THRESH_BINARY_INV二值化gray得到binary,并显示二值化的图像。调整阈值使显示出来的二值化图像包含车牌区域
# 此处阈值需要根据具体图像情况适当调整,示例中只是初始值
ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY_INV)
cv.imshow('Binary Image', binary)
cv.waitKey(0)
# 4. 使用3x3的卷积核腐蚀1次,去掉图像右下角水印
kernel_erode_1 = np.ones((3, 3), np.uint8)
eroded_1 = cv.erode(binary, kernel_erode_1, iterations=1)
# 5. 使用5x5卷积核膨胀3次,使二值化的图像中车牌区域全为白色
kernel_dilate = np.ones((5, 5), np.uint8)
dilated = cv.dilate(eroded_1, kernel_dilate, iterations=3)
# 6. 使用5x5卷积核腐蚀3次,使二值化的图像中车牌区域恢复到接近原车牌面积
kernel_erode_2 = np.ones((5, 5), np.uint8)
eroded_2 = cv.erode(dilated, kernel_erode_2, iterations=3)
# 7. 对上述结果进行轮廓查找:cv.findContours
contours, hierarchy = cv.findContours(eroded_2, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
# 8. 遍历所有轮廓:
# 计算并打印轮廓的面积
# 在原图上绘制轮廓
for contour in contours:
area = cv.contourArea(contour)
print("面积:", area)
cv.drawContours(img, [contour], -1, (0, 255, 0), 2)
# 9. 将最终绘制后的图像显示出来
cv.imshow('img', img)
cv.waitKey(0)
cv.destroyAllWindows()