python多进程读图提取特征存npy
作者:业余狙击手19 发布时间:2022-09-05 11:38:06
标签:python,多进程,提取特征
本文实例为大家分享了python多进程读图提取特征存npy的具体代码,供大家参考,具体内容如下
import multiprocessing
import os, time, random
import numpy as np
import cv2
import os
import sys
from time import ctime
import tensorflow as tf
image_dir = r"D:/sxl/处理图片/汉字分类/train10/" #图像文件夹路径
data_type = 'test'
save_path = r'E:/sxl_Programs/Python/CNN/npy/' #存储路径
data_name = 'Img10' #npy文件名
char_set = np.array(os.listdir(image_dir)) #文件夹名称列表
np.save(save_path+'ImgShuZi10.npy',char_set) #文件夹名称列表
char_set_n = len(char_set) #文件夹列表长度
read_process_n = 1 #进程数
repate_n = 4 #随机移动次数
data_size = 1000000 #1个npy大小
shuffled = True #是否打乱
#可以读取带中文路径的图
def cv_imread(file_path,type=0):
cv_img=cv2.imdecode(np.fromfile(file_path,dtype=np.uint8),-1)
# print(file_path)
# print(cv_img.shape)
# print(len(cv_img.shape))
if(type==0):
if(len(cv_img.shape)==3):
cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
return cv_img
#多个数组按同一规则打乱数据
def ShuffledData(features,labels):
'''
@description:随机打乱数据与标签,但保持数据与标签一一对应
'''
permutation = np.random.permutation(features.shape[0])
shuffled_features = features[permutation,:] #多维
shuffled_labels = labels[permutation] #1维
return shuffled_features,shuffled_labels
#函数功能:简单网格
#函数要求:1.无关图像大小;2.输入图像默认为灰度图;3.参数只有输入图像
#返回数据:1x64*64维特征
def GetFeature(image):
#图像大小归一化
image = cv2.resize(image,(64,64))
img_h = image.shape[0]
img_w = image.shape[1]
#定义特征向量
feature = np.zeros(img_h*img_w,dtype=np.int16)
for h in range(img_h):
for w in range(img_w):
feature[h*img_h+w] = image[h,w]
return feature
# 写数据进程执行的代码:
def read_image_to_queue(queue):
print('Process to write: %s' % os.getpid())
for j,dirname in enumerate(char_set): # dirname 是文件夹名称
label = np.where(char_set==dirname)[0][0] #文件夹名称对应的下标序号
print('序号:'+str(j),'读 '+dirname+' 文件夹...时间:',ctime() )
for parent,_,filenames in os.walk(os.path.join(image_dir,dirname)):
for filename in filenames:
if(filename[-4:]!='.jpg'):
continue
image = cv_imread(os.path.join(parent,filename),0)
# cv2.imshow(dirname,image)
# cv2.waitKey(0)
queue.put((image,label))
for i in range(read_process_n):
queue.put((None,-1))
print('读图结束!')
return True
# 读数据进程执行的代码:
def extract_feature(queue,lock,count):
'''
@description:从队列中取出图片进行特征提取
@queue:先进先出队列
lock:锁,在计数时上锁,防止冲突
count:计数
'''
print('Process %s start reading...' % os.getpid())
global data_n
features = [] #存放提取到的特征
labels = [] #存放标签
flag = True #标志着进程是否结束
while flag:
image,label = queue.get() #从队列中获取图像和标签
if len(features) >= data_size or label == -1: #特征数组的长度大于指定长度,则开始存储
array_features = np.array(features) #转换成数组
array_labels = np.array(labels)
array_features,array_labels = ShuffledData(array_features,array_labels) #打乱数据
lock.acquire() # 锁开始
# 拆分数据为训练集,测试集
split_x = int(array_features.shape[0] * 0.8)
train_data, test_data = np.split(array_features, [split_x], axis=0) # 拆分特征数据集
train_labels, test_labels = np.split(array_labels, [split_x], axis=0) # 拆分标签数据集
count.value += 1 #下标计数加1
str_features_name_train = data_name+'_features_train_'+str(count.value)+'.npy'
str_labels_name_train = data_name+'_labels_train_'+str(count.value)+'.npy'
str_features_name_test = data_name+'_features_test_'+str(count.value)+'.npy'
str_labels_name_test = data_name+'_labels_test_'+str(count.value)+'.npy'
lock.release() # 锁释放
np.save(save_path+str_features_name_train,train_data)
np.save(save_path+str_labels_name_train,train_labels)
np.save(save_path+str_features_name_test,test_data)
np.save(save_path+str_labels_name_test,test_labels)
print(os.getpid(),'save:',str_features_name_train)
print(os.getpid(),'save:',str_labels_name_train)
print(os.getpid(),'save:',str_features_name_test)
print(os.getpid(),'save:',str_labels_name_test)
features.clear()
labels.clear()
if label == -1:
break
# 获取特征向量,传入灰度图
feature = GetFeature(image)
features.append(feature)
labels.append(label)
# # 随机移动4次
# for itime in range(repate_n):
# rMovedImage = randomMoveImage(image)
# feature = SimpleGridFeature(rMovedImage) # 简单网格
# features.append(feature)
# labels.append(label)
print('Process %s is done!' % os.getpid())
if __name__=='__main__':
time_start = time.time() # 开始计时
# 父进程创建Queue,并传给各个子进程:
image_queue = multiprocessing.Queue(maxsize=1000) #队列
lock = multiprocessing.Lock() #锁
count = multiprocessing.Value('i',0) #计数
#将图写入队列进程
write_sub_process = multiprocessing.Process(target=read_image_to_queue, args=(image_queue,))
read_sub_processes = [] #读图子线程
for i in range(read_process_n):
read_sub_processes.append(
multiprocessing.Process(target=extract_feature, args=(image_queue,lock,count))
)
# 启动子进程pw,写入:
write_sub_process.start()
# 启动子进程pr,读取:
for p in read_sub_processes:
p.start()
# 等待进程结束:
write_sub_process.join()
for p in read_sub_processes:
p.join()
time_end=time.time()
time_h=(time_end-time_start)/3600
print('用时:%.6f 小时'% time_h)
print ("读图提取特征存npy,运行结束!")
来源:https://blog.csdn.net/sxlsxl119/article/details/89340318


猜你喜欢
- 添加字段的语法:alter table tablename add (column datatype [default value][nul
- 小的本身是一个平面设计人员,前一阵儿有一些空闲的时间,便在各个站长网上发布了贴子,大意是免费制作logo,以换取网站连接(相信很多人都看过)
- 当然有其它工具可以做这件事,但如果客户不允许你在服务器乱装东西时这个脚本就会有用了。 DECLARE @tbImportTables tab
- # -*- coding: GBK -*- from ctypes import * dll = windll.LoadLibrary(&#
- 这是一个系列文章,主要分享python的使用建议和技巧,每次分享3点,希望你能有所收获。1 如何去掉list中重复元素my_list = [
- 以下是Python基础学习内容的学习笔记的全部内容,非常的详细,如果你对Python语言感兴趣,并且针对性的系统学习一下基础语言知识,下面的
- 一、merge(合并)的语法:pd.merge(left, right, how='inner', on=None, lef
- 数据类型计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值。但是,计算机能处理的远不止数值,还可以处理文本、
- 本文实例讲述了Python画柱状统计图操作。分享给大家供大家参考,具体如下:一、工具:python的matplotlib.pyplot 库二
- 录入身份证信息是一件繁琐的工作,如果可以自动识别并且录入系统,那可真是太好了。今天我们就来学习一下,如何自动识别身份证信息并且录入系统~识别
- 一个单独的组件注释写了一个组件 加了一些注释效果图如下分页一类的功能都已经写好了 下面就上代码,不知道有几个老哥能看的懂,有不足之处,还望老
- PyQt5布局控件QGridLayout简介QGridLayout(网格布局)是将窗口分割成行和列的网格来进行排列,通常可以使用函数addW
- 基本开发环境· Python 3.6· Pycharm需要导入的库目标网页分析网站是静态网站,没有加密,可以直接爬取整体思路:1、先在列表页
- DataSource是作为DriverManager的替代品而推出的,DataSource 对象是获取连接的首选方法。起源为何放弃Drive
- 离散特征的编码分为两种情况: 1、离散特征的取值之间没有大小的意义,比如color:[red,blue],那么就使用one-hot编码2、离
- 本文实例讲述了Python爬虫之pandas基本安装与使用方法。分享给大家供大家参考,具体如下:一、简介:Python Data Analy
- 如何用SA-FileUp上传多个文件?表单处理: <%@&nbs
- 本文实例讲述了python实现ip代理池功能。分享给大家供大家参考,具体如下:爬取的代理源为西刺代理。用xpath解析页面用telnet来验
- 本文实例为大家分享了python爬取微信公众号文章的具体代码,供大家参考,具体内容如下该方法是依赖于urllib2库来完成的,首先你需要安装
- 新版的path 虽然 取代了 之前的url,但是在写路由的时候不能在路由中直接写正则表达式,不然会找不到页面。解决方法使用re_pathfr