【11】python根据图像处理的三维特征绘制三维散点图

【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】参考

Python中scatter函数参数详解

plt.subplot()函数解析

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值