2017-11-28 63 views
2

나는 이미지를 자르고 저장하는 간단한 코드를 작성 중이다.
그러나 문제는 이미지의 수가 약 150,000 이상이며 속도를 향상시키고 싶다는 것입니다.
파이썬 다중 처리 - 속도 개선을 위해 작업량을 어떻게 분할 할 수 있습니까?

그래서 처음에 나는 다음과 같이 루프에 대한 간단한으로 코드를 작성 :

import cv2 
import numpy 
import sys 

textfile=sys.argv[1] 
file_list=open(textfile) 
files=file_list.read().split('\n') 
idx=0 
for eachfile in files: 
    image=cv2.imread(eachfile) 
    idx+=1 
    if image is None: 
     pass 
    outName=eachfile.replace('/data','/changed_data') 
    if image.shape[0]==256: 
     image1=image[120:170,120:170] 
    elif image.shape[0]==50: 
     image1=image 
    cv2.imwrite(outName,image1) 
    print idx,outName 

이 코드는 90000 개 이미지를 약 38 초 걸렸습니다. 그러나 이중 코어를 사용하면 단일 프로세스보다 시간이 오래 걸렸으며 동일한 90000 이미지의 경우 약 48 초가 소요되었습니다.

import cv2 
import sys 
import numpy 
from multiprocessing import Pool 

def crop(eachfile): 
    image=cv2.imread(eachfile) 
    idx+=1 
    if image is None: 
     pass 
    outName=eachfile.replace('/data','/changed_data') 
    if image.shape[0]==256: 
     image1=image[120:170,120:170] 
    elif image.shape[0]==50: 
     image1=image 
    cv2.imwrite(outName,image1) 
    print idx,outName 


if __name__=='__main__': 
    textfile=sys.argv[1] 
    file_list=open(textfile) 
    files=file_list.read().split('\n') 
    pool=Pool(2) 
    pool.map(crop,files) 

나는 프로세스 속도를 높이기 위해 올바른 일을하고 있습니까? 또는 목록을 분리하고 각 목록을 프로세스에 보내야합니까?

의견에 감사드립니다 내 코드는 좋아요 !!!

미리 감사드립니다.

+0

BTW, 프로그램은 \ n 문자로 구분 파일과 텍스트 파일을 읽고 있습니다. – user103192

답변

0

당신은 실제로 두 개의 코어를 통해 작업을 분할해야한다. 이 예제 코드로 "약간 수정했다". OP는 here입니다. 귀하의 이미지를 제공하는 귀하의 후크 인 data이있는 곳. defs는 클래스에서 multiprocessing을 사용할 때 작동하지 않습니다 ... 만약 당신이 pathos를 사용하려고하면 ... cPickle ...에서 최신 2.7 버전의 잔소리가 나는 문제가 발생할 것입니다. 3.5 등에서는 발생하지 않습니다. 즐겨!

import multiprocessing 

def mp_worker((inputs, the_time)): 
    print " Process %s\tWaiting %s seconds" % (inputs, the_time) 
    time.sleep(int(the_time)) 
    print " Process %s\tDONE" % inputs 
    sys.stdout.flush() 

def mp_handler():       # Non tandem pair processing 
    p = multiprocessing.Pool(2) 
    p.map(mp_worker, data) 

def mp_handler_tandem(): 
    subdata = zip(data[0::2], data[1::2]) 
# print subdata 
    for task1, task2 in subdata: 
     p = multiprocessing.Pool(2) 
     p.map(mp_worker, (task1, task2)) 

#data = (['a', '1'], ['b', '2'], ['c', '3'], ['d', '4']) 
data = (['a', '2'], ['b', '3'], ['c', '1'], ['d', '4'], 
     ['e', '1'], ['f', '2'], ['g', '3'], ['h', '4']) 

if __name__ == '__main__': 
    sys.stdout.flush() 
# print 'mp_handler():' 
# mp_handler() 
# print '---' 
# time.sleep(2) 

# print '\nmp_handler_tandem():' 
# mp_handler_tandem() 
    print '---' 
# time.sleep(2) 

    Multiprocess().qmp_handler() 

편집기 내에서 작업 : 그런 일 동안 화면에 출력을 플러시 sys.stdout.flush()를 사용합니다.

그러나 커널 및 분할 작업을 사용하여 here도 확인하십시오.