【1】背景介紹
本文代碼是檢測一個物體的特徵包含面積,圓度,周長,然後生產一個三維散點圖。
【2】圖像處理類(ConcludeFeature.py)
import cv2
import numpy as np
import math
class ConcludeFeatures:
#初始化參數
def __init__(self, image):
self.image= image
#圖像預處理
def pre_process(self):
grayImg= cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
r, threImg = cv2.threshold(grayImg, 102, 255, cv2.THRESH_BINARY_INV)
return threImg
#計算圓度
def compute_roundness(self):
contours, hierarchy = cv2.findContours(np.array(self.image, dtype=np.uint8), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
numbercontous=len(contours)
a = cv2.contourArea(contours[0]) * 4 * math.pi
b = math.pow(cv2.arcLength(contours[0], True), 2)
if b == 0:
return 0
return a / b
#計算周長
def copute_length(self):
contours, hierarchy = cv2.findContours(np.array(self.image, dtype=np.uint8), cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
length=cv2.arcLength(contours[0], True)
return length
#計算面積
def compute_area(self):
contours, hierarchy = cv2.findContours(np.array(self.image, dtype=np.uint8), cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
area = cv2.contourArea(contours[0])
return area
【3】圖像數據導入類(dataprocess)
import os
import cv2
#載入圖片 處理後保存到一個文件夾
def read__image(open_path,save_path):
nums=0
images=[]
for dir_image in os.listdir(open_path): # os.listdir() 方法用於返回指定的文件夾包含的文件或文件夾的名字的列表
full_path = os.path.abspath(os.path.join(open_path,dir_image))
if dir_image.endswith('.bmp'):
image = cv2.imread(full_path)
image_path = save_path+'%s-%s.jpg' % ('Cell',str(nums))
cv2.imwrite(image_path, image)
nums=nums+1
#載入圖片,處理後保存到一個列表中
def GetImg(open_path):
patch=[]
for dir_image in os.listdir(open_path): # os.listdir() 方法用於返回指定的文件夾包含的文件或文件夾的名字的列表
full_path = os.path.abspath(os.path.join(open_path,dir_image))
if dir_image.endswith('.jpg'):
image = cv2.imread(full_path)
#resImg=cv2.resize(image,(227,227))
patch.append(image)
return patch
【4】主程序(main.py)
import cv2
import numpy as np
from ConcludeFeature import *
from dataprocess import GetImg
import matplotlib.pyplot as plt
from sklearn import preprocessing
img=cv2.imread("1.bmp",1)
picpath='D:\\pythonprocedure\\FeaturesDection\\4539class\\'
presave='D:\\pythonprocedure\\FeaturesDection\\4539threshold\\'
imgs=[]
imgs=GetImg(picpath)
featurepoint=[]
for index in range(len(imgs)):
#preprocess image
grayImg= cv2.cvtColor(imgs[index], cv2.COLOR_BGR2GRAY)
r, threImg = cv2.threshold(grayImg, 102, 255, cv2.THRESH_BINARY_INV)
#save image
image_path = presave+'%s-%s.jpg' % ('precell',str(index))
cv2.imwrite(image_path, threImg)
#計算特徵參數
conclude=ConcludeFeatures(threImg)
area=conclude.compute_area()
#保留三位有效數字
area=round(area,3)
roundness=conclude.compute_roundness()
roundness=round(roundness,3)
length=conclude.copute_length()
length=round(length,3)
#特徵結果保存
point=[area,roundness,length]
featurepoint.append(point)
#列表轉換爲數組
featurearray=np.array(featurepoint)
#數組歸一化
min_max_scaler = preprocessing.MinMaxScaler()
featurearray_minmax = min_max_scaler.fit_transform(featurearray)
#可視化
# 創建一個三維的繪圖工程
#繪製歸一化後的結果圖
ax=plt.subplot(121, projection='3d')
for index_point in range(len(featurearray_minmax)):
x, y, z = featurearray_minmax[index_point][0], featurearray_minmax[index_point][1], featurearray_minmax[index_point][2]
ax.scatter(x,y,z,s=1,c = 'r',marker = 'o')
ax.set_zlabel('Z-length') # 座標軸
ax.set_ylabel('Y-roundness')
ax.set_xlabel('X-area')
#繪製未歸一化的圖
ax2=plt.subplot(122, projection='3d')
for index_point in range(len(featurearray)):
x, y, z = featurearray[index_point][0], featurearray[index_point][1], featurearray[index_point][2]
ax2.scatter(x,y,z,s=1,c = 'r',marker = 'o')
ax2.set_zlabel('Z-length') # 座標軸
ax2.set_ylabel('Y-roundness')
ax2.set_xlabel('X-area')
#scatter(x,y,z,s=10,c = 'b',linewidths=5,marker = 'p')
'''
c:標記點的大小,linewidth:線寬,marker:標記點的形狀
'''
#顯示結果圖
plt.show()
cv2.waitKey()
【5】結果展示
【6】參考