python多进程读图提取特征存npy


Posted in Python onMay 21, 2019

本文实例为大家分享了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,运行结束!")

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python生成器表达式和列表解析
Mar 10 Python
Python语言的面相对象编程方式初步学习
Mar 12 Python
Python缩进和冒号详解
Jun 01 Python
python3 破解 geetest(极验)的滑块验证码功能
Feb 24 Python
Python使用googletrans报错的解决方法
Sep 25 Python
深入解析python中的实例方法、类方法和静态方法
Mar 11 Python
python多线程抽象编程模型详解
Mar 20 Python
python库matplotlib绘制坐标图
Oct 18 Python
Python函数的返回值、匿名函数lambda、filter函数、map函数、reduce函数用法实例分析
Dec 26 Python
python orm 框架中sqlalchemy用法实例详解
Feb 02 Python
为什么称python为胶水语言
Jun 16 Python
用python获取txt文件中关键字的数量
Dec 24 Python
Python中使用pypdf2合并、分割、加密pdf文件的代码详解
May 21 #Python
python+selenium实现简历自动刷新的示例代码
May 20 #Python
图文详解python安装Scrapy框架步骤
May 20 #Python
Python配置虚拟环境图文步骤
May 20 #Python
Python检测数据类型的方法总结
May 20 #Python
Python中的引用知识点总结
May 20 #Python
Python函数和模块的使用总结
May 20 #Python
You might like
dedecms后台验证码总提示错误的解决方法
2007/03/21 PHP
php采集速度探究总结(原创)
2008/04/18 PHP
帝国cms目录结构分享
2015/07/06 PHP
Discuz不使用插件实现简单的打赏功能
2019/03/21 PHP
(仅IE下有效)关于checkbox 三态
2007/05/12 Javascript
jQuery中使用了document和window哪些属性和方法小结
2011/09/13 Javascript
javascript监听鼠标滚轮事件浅析
2014/06/05 Javascript
js实现延迟加载的方法
2015/06/24 Javascript
JavaScript实现开关等效果
2017/09/08 Javascript
浅谈JavaScript中的属性:如何遍历属性
2017/09/14 Javascript
jQuery实现火车票买票城市选择切换功能
2017/09/15 jQuery
ExtJs整合Echarts的示例代码
2018/02/27 Javascript
深入理解JS的事件绑定、事件流模型
2018/05/13 Javascript
更改BootStrap popover的默认样式及popover简单用法
2018/09/13 Javascript
解决Vue使用swiper动态加载数据,动态轮播数据显示白屏的问题
2018/09/27 Javascript
一个Java程序猿眼中的前后端分离以及Vue.js入门(推荐)
2019/04/19 Javascript
JavaScript中判断为整数的多种方式及保留两位小数的方法
2019/09/09 Javascript
Python中AND、OR的一个使用小技巧
2015/02/18 Python
Python功能键的读取方法
2015/05/28 Python
pygame加载中文名mp3文件出现error
2017/03/31 Python
python3.6+opencv3.4实现鼠标交互查看图片像素
2018/02/26 Python
python批量设置多个Excel文件页眉页脚的脚本
2018/03/14 Python
django框架model orM使用字典作为参数,保存数据的方法分析
2019/06/24 Python
python实现的按要求生成手机号功能示例
2019/10/08 Python
python异常处理try except过程解析
2020/02/03 Python
django API 中接口的互相调用实例
2020/04/01 Python
pytorch下的unsqueeze和squeeze的用法说明
2021/02/06 Python
美国战术品牌:5.11 Tactical
2019/05/01 全球购物
介绍一下Linux内核的排队自旋锁
2014/01/04 面试题
会计专业毕业生自我评价
2013/09/25 职场文书
故意伤害罪辩护词
2015/05/21 职场文书
聚众斗殴罪辩护词
2015/05/21 职场文书
2016年寒假政治学习心得体会
2015/10/09 职场文书
nginx基于域名,端口,不同IP的虚拟主机设置的实现
2021/03/31 Servers
带你彻底理解JavaScript中的原型对象
2021/04/14 Javascript
AJAX实现省市县三级联动效果
2021/10/16 Javascript