初尝图像识别
程序员文章站
2022-04-05 19:45:52
...
第一次接触图像识别是在2019的亚太数学建模上当时选择的是A题
利用photoshop对图像进行处理和提取
- 利用Python寻找SiO2的轮廓坐标
import numpy as np
num = 497
while(num<=610):
print(num)
str1 = '%d'%num
str = 'C:\\Users\\Li\\PycharmProjects\\Demo\\0'+str1+'.jpg'
img = cv2.imread(str)
num=num+1
img_original=cv2.imread(str)
img_gray=cv2.cvtColor(img_original,cv2.COLOR_BGR2GRAY)
#求二值图像
retv,thresh=cv2.threshold(img_gray,125,255,1)
#寻找轮廓
contours,hierarchy=cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#绘制轮廓
cv2.drawContours(img_original,contours,-1,(0,0,255),3,lineType=cv2.LINE_AA)
#显示图像
#cv2.imshow('Contours',img_original)
#cv2.namedWindow('Contours',0)
cv2.waitKey()
cv2.destroyAllWindows()
#print(hierarchy)
#print(contours[1])
str2 = 'C:\\Users\\Li\\PycharmProjects\\Demo\\data\\'+str1+'.txt'
data = open(str2, 'w+')
print(contours[1], file=data)
data.close()
- 利用Python寻找SiO2的面积、周长、质心
import numpy as np
num = 497
while(num<=610):
str1 = '%d'%num
str = 'C:\\Users\\Li\\PycharmProjects\\Demo\\0'+str1+'.jpg'
img = cv2.imread(str)
num=num+1
#print("坐标为"+str1)
ret,thresh = cv2.threshold(cv2.cvtColor(img,cv2.COLOR_BGR2GRAY),127,255,0)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)#得到轮廓信息
cnt = contours[0]#取第一条轮廓
M = cv2.moments(cnt)#计算第一条轮廓的矩
imgnew = cv2.drawContours(img, contours, -1, (0,255,0), 3)#把所有轮廓画出来
#print (M)
#这两行是计算中心点坐标
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
#计算轮廓所包含的面积
area = cv2.contourArea(cnt)
#计算轮廓的周长
perimeter = cv2.arcLength(cnt,True)
#轮廓的近似
epsilon = 0.02*perimeter
approx = cv2.approxPolyDP(cnt,epsilon,True)
imgnew1 = cv2.drawContours(img, approx, -1, (0,0,255), 3)
#cv2.imshow('lunkuo',imgnew)
#cv2.imshow('approx_lunkuo',imgnew1)
#print(str[33:37])
#print("面积")
#print(area)
#print("周长")
#print(perimeter)
#print("中心点坐标")
#print(cx)
#print(cy)
#print()
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
cv2.waitKey(0)
下一篇: 递推算法3——顺推法之母牛生小牛问题