本文主要是介绍opencv-python利用k均值算法完成焊点识别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#draw.用来画图
import cv2import numpy as np #mouse callback functionfrom knn import *ix,iy=-1,-1#创建图像与窗口并将窗口与回调函数绑定def in_img():for i in range(512):img[i, ] = 255cv2.namedWindow('image')cv2.setMouseCallback('image',draw_circle)for i in range(1,4):for j in range(10):while 1:cv2.imshow('image', img)if cv2.waitKey(20) & 0xFF == ord('q'):cv2.imwrite('testDigits'+'\\'+str(i)+str(j)+'.jpg', img)for k in range(512):img[k, ] = 255break# while 1:# cv2.imshow('image', img)# if cv2.waitKey(20)&0XFF == ord('q'):# cv2.imwrite('1.jpg', img)# breakcv2.destroyAllWindows()def draw_circle(event,x,y,flags,param):global ix,iy,drawingif event==cv2.EVENT_LBUTTONDOWN:drawing=Trueix,iy=x,yelif event==cv2.EVENT_MOUSEMOVE and flags==cv2.EVENT_FLAG_LBUTTON:if drawing==True:cv2.circle(img,(x,y),30,(0,0,0),-1)elif event==cv2.EVENT_LBUTTONUP:drawing==Falsedef read_image():img1 = cv2.imread('1.jpg', cv2.IMREAD_GRAYSCALE)res=cv2.resize(img1,(32,32),interpolation=cv2.INTER_CUBIC)pic=[]for i in range(32):for j in range(32):if res[i][j]<=200:res[i][j]=1else:res[i][j]=0pic.append(int(res[i][j]))hwLabels,trainingMat = trainingDataSet()classifierResult = classify(pic, trainingMat, hwLabels, 3)print( classifierResult)def main():global imgimg=np.zeros((512,512,3),np.uint8)in_img()read_image()if __name__=="__main__":main()#handiantest.py,可以直接测试,不用KNN.PY
import numpy as np
import cv2a = 10(event,x,y,flags,param):if event == cv2.EVENT_LBUTTONDOWN:print("HSV is", HSV[y, x])def getpos1(event,x,y,flags,param):if event == cv2.EVENT_LBUTTONDOWN:print("mask_image isy",y ,x , mask_image[y, x])def getpos2(event,x,y,flags,param):if event == cv2.EVENT_LBUTTONDOWN:print("mask is", y, x,mask[y, x])def calculateCountourArea(image, src):print("hsv", image.shape)image1 = image.copy()# 如果color中定义了几种颜色区间,都可以分割出来for (lower, upper) in color:# 创建NumPy数组lower = np.array(lower, dtype="uint8") # 颜色下限upper = np.array(upper, dtype="uint8") # 颜色上限# 根据阈值找到对应颜色mask1 = cv2.inRange(image1, lower, upper) # 查找处于范围区间的kernel1 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 构造腐蚀核mask1 = cv2.erode(mask1, kernel1)mask1 = cv2.dilate(mask1, kernel1)ret1, mask1 = cv2.threshold(mask1, 0.5, 255, cv2.THRESH_BINARY)cv2.imshow("形态学处理", mask1)# 二值化ret1, binarry1 = cv2.threshold(mask1, 0.5, 1, cv2.THRESH_BINARY)mask_image1, contours1, hierarchy1 = cv2.findContours(binarry1, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)area1 = []# 找到最大的轮廓for k1 in range(len(contours1)):area1.append(cv2.contourArea(contours1[k1]))max_idx1 = np.argmax(np.array(area1))print(len(contours1))cv2.drawContours(src, contours1, -1, (0, 0, 255), 1)for i in contours1:print(cv2.contourArea(i)) # 计算缺陷区域面积x, y, w, h = cv2.boundingRect(i) # 画矩形框cv2.rectangle(src, (x, y), (x + w, y + h), (0, 255, 0), 1)cv2.imshow("src", src)# 读 取 图 片
img = cv2.imread("C:/Users/asus/Desktop/Inkedpaomo_LI.jpg", 1)# 直接读为灰度图像
# 可以缩小图像
height, width = img.shape[:2]
size = (int(width ), int(height )) # bgr
img = cv2.resize(img, size, interpolation=cv2.INTER_AREA)
#BGR转化为HSV
HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imshow("HSV", HSV)
print("hsv", HSV.shape)
cv2.setMouseCallback("imageHSV", getpos)
color = [([0, 0, 90], [165, 30, 240]) # 蓝色范围~这个是我自己试验的范围,可根据实际情况自行调整~注意:数值按[b,g,r]排布
]
# 如果color中定义了几种颜色区间,都可以分割出来
for (lower, upper) in color:# 创建NumPy数组lower = np.array(lower, dtype="uint8") # 颜色下限upper = np.array(upper, dtype="uint8") # 颜色上限# 根据阈值找到对应颜色mask = cv2.inRange(HSV, lower, upper) #查找处于范围区间的#cv2.imshow("mask", mask)
print("mask", mask.shape)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) # 构造腐蚀核
mask = cv2.erode(mask, kernel)
mask = cv2.dilate(mask, kernel)
ret, mask = cv2.threshold(mask, 0.5, 255, cv2.THRESH_BINARY)
cv2.imshow("形态学处理", mask)
#二值化
ret, binarry = cv2.threshold(mask, 0.5, 1, cv2.THRESH_BINARY)
mask_image, contours, hierarchy = cv2.findContours(binarry, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
mask_image = mask.copy()
#mask = mask-mask
#cv2.imshow('mask_image1', mask_image)
#cv2.imshow('mask_', mask)
area = []
# 找到最大的轮廓
for k in range(len(contours)):area.append(cv2.contourArea(contours[k]))
max_idx = np.argmax(np.array(area))
#填充最大的轮廓
for k in range(len(contours)):if(k == max_idx):mask = cv2.drawContours(mask, contours, max_idx, 255, cv2.FILLED)else:mask = cv2.drawContours(mask, contours, k, 0, cv2.FILLED)mask = cv2.drawContours(mask, contours, max_idx, 255, cv2.FILLED)cv2.imshow("mask", mask)
cv2.imshow('mask_image', mask_image)
cv2.setMouseCallback("mask", getpos2)
cv2.setMouseCallback("mask_image", getpos1)
output = cv2.bitwise_and(mask, mask_image)
cv2.imshow("output", output)
new_hsv = cv2.bitwise_and(HSV, HSV, mask=output)
cv2.imshow("img", new_hsv)
#bgroutput = cv2.cvtColor(output, cv2.COLOR_HSV2BGR)
# 展示图片
#cv2.imshow("images", np.hstack([img, output]))
calculateCountourArea(new_hsv, img)cv2.waitKey(0)#knn.py
from numpy import *import operatorimport timefrom os import listdirdef classify(inputPoint,dataSet,labels,k):dataSetSize = dataSet.shape[0] #已知分类的数据集(训练集)的行数#先tile函数将输入点拓展成与训练集相同维数的矩阵,再计算欧氏距离diffMat = tile(inputPoint,(dataSetSize,1))-dataSet #样本与训练集的差值矩阵sqDiffMat = diffMat ** 2 #差值矩阵平方sqDistances = sqDiffMat.sum(axis=1) #计算每一行上元素的和distances = sqDistances ** 0.5 #开方得到欧拉距离矩阵sortedDistIndicies = distances.argsort() #按distances中元素进行升序排序后得到的对应下标的列表#选择距离最小的k个点classCount = {}for i in range(k):voteIlabel = labels[ sortedDistIndicies[i] ]classCount[voteIlabel] = classCount.get(voteIlabel,0)+1#按classCount字典的第2个元素(即类别出现的次数)从大到小排序sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)return sortedClassCount[0][0]def img2vector(filename):returnVect = []fr = open(filename)for i in range(32):lineStr = fr.readline()for j in range(32):returnVect.append(int(lineStr[j]))return returnVectdef classnumCut(fileName):fileStr = fileName.split('.')[0]classNumStr = int(fileStr.split('_')[0])return classNumStr#构建训练集数据向量,及对应分类标签向量def trainingDataSet():hwLabels = []trainingFileList = listdir('trainingDigits1') #获取目录内容m = len(trainingFileList)trainingMat = zeros((m,1024)) #m维向量的训练集for i in range(m):fileNameStr = trainingFileList[i]hwLabels.append(classnumCut(fileNameStr))trainingMat[i,:] = img2vector('trainingDigits1/%s' % fileNameStr)#print type(trainingMat)return hwLabels,trainingMat
这篇关于opencv-python利用k均值算法完成焊点识别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!