亚洲免费在线-亚洲免费在线播放-亚洲免费在线观看-亚洲免费在线观看视频-亚洲免费在线看-亚洲免费在线视频

python多進程讀圖提取特征存npy

系統 1657 0

本文實例為大家分享了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,運行結束!")
          

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 亚洲精品视频久久久 | jizz人妖| 开心久久婷婷综合中文字幕 | 在线欧美69v免费观看视频 | 伊人狼人视频 | 国产亚洲精品在天天在线麻豆 | 久久欧美 | 一级毛片免费不卡在线 | 久久精品夜色国产 | 久久亚洲国产精品五月天婷 | 精品日韩在线观看 | 国模极品一区二区三区 | 91亚洲国产三上悠亚在线播放 | 涩涩免费视频 | 欧美爽爽 | 中文字幕日本不卡一二三区 | 国产精品爱久久 | 成人美女隐私免费 | 毛片激情永久免费 | 99re久久在热线播放最新地址 | 97国产影院| 久久精品国产国产精品四凭 | 九九99热久久精品在线6手机 | 伊人久久波多野结衣中文字幕 | 久久久久国产精品免费网站 | 久久成人精品免费播放 | 爱操影院 | 国产精彩视频在线 | 亚洲韩精品欧美一区二区三区 | 久久亚洲美女久久久久 | 久久99国产精一区二区三区 | 国产成人精品视频播放 | 波多野结衣一区免费作品 | 免费一级欧美片在线观免看 | 国产成人+亚洲欧洲 | 狠狠躁日日躁人人爽 | 久草免费公开视频 | 图片区亚洲 | 日本不卡一二三区 | 德国女人一级毛片免费 | 国产精品亚洲二线在线播放 |