运用opencv完成的基本的预处理操作
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
def recognition(img):
#灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow(‘gray‘, gray)
cv2.waitKey(0)
#二值化
ret, binary = cv2.threshold(gray, 109, 255, cv2.THRESH_BINARY)
cv2.imshow(‘binary‘, binary)
cv2.waitKey(0)
#膨胀腐蚀操作的核函数
element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
#膨胀
dilation = cv2.dilate(binary, element1, iterations=1)
#腐蚀
erosion = cv2.erode(dilation, element2, iterations=1)
cv2.imshow(‘close‘, erosion)
cv2.waitKey(0)
#canny算子求轮廓
canny = cv2.Canny(erosion, 100, 200)
cv2.imshow(‘canny‘, canny)
cv2.waitKey(0)
#识别轮廓
image, contours, hierarchy = cv2.findContours(canny, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#绘制轮廓
cv2.drawContours(img, contours, -1, (0, 0, 255), 3)
cv2.imshow(‘contours‘, img)
cv2.waitKey(0)
print(‘总数:‘ + str(len(contours)//2))
imgpath = ‘test.jpg‘
img = cv2.imread(imgpath)
recognition(img)