如何使用多处理并行处理OpenCV的图像? [英] How can I process images with OpenCV in parallel using multiprocessing?
问题描述
我要使用某些OpenCV函数预处理的文件夹中有一组图像.函数
I have a set of images in a folder that I want to preprocess using some OpenCV functions. The function
detectAndaligncrop
拍摄一个图像路径,使用OpenCV对其进行预处理,然后返回utput图像. 我可以使用:
takes an image path preprocesses it using OpenCV and returns the utput image. I am able to do it using:
for image_path in files_list:
cropped_image, _=detectAndaligncrop(im)
cv2.imwrite("ouput_folder/{}".format(os.path.basename(image_path)),cropped_im*255.)
但是这不起作用:
jobs=[]
for im_no, im in enumerate(files_list):
p=multiprocessing.Process(target=saveIm,args=[im])
jobs.append(p)
p.start()
for j in jobs:
j.join()
其中saveIm是:
im,lm=detectAndaligncrop(im_path)
fname="output_path/cropped2/{}".format(os.path.basename(im_path))
cv2.imwrite(fname,im)
我已经验证它调用了detectAndaligncrop函数,但是没有处理从其中的行开始的图像
I have verified that it calls the detectAndaligncrop function, but does not process image starting from the line where
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
在detectAndaligncrop内部被调用,因为每个图像都调用"before cvtColor",而"cvtColor after"则不是:
is called inside detectAndaligncrop, because "before cvtColor" is called for every image, while "after cvtColor" is not:
def detectAndaligncrop(impath):
image=cv2.imread(impath)
image_float=np.float32(image)/255.0
print ("before cvtcolor")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
print ("after cvtcolor")
return gray, 1
我也尝试过:
with ThreadPoolExecutor(max_workers=32) as execr:
res=execr.map(saveIm,files_list)
此方法有效,但仅比运行for循环快.是因为GIL吗?
This works but no faster than simply running a for loop. Is it because of GIL?
推荐答案
经过几次实验后发现错误: 基本上,错误在于将读取的图像转换为灰度图像的方法. 如果我使用:
After a few experiments found the error: Basically, the error is in the method to convert the read image into a grayscale one. If I use :
gray = cv2.imread(impath,0)
代替
image = cv2.imread(impath)
image_float = np.float32(image)/255.0
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
代码工作正常,
在MultiProcessing中使用cv2.cvtColor可能存在一些问题.有人可以阐明原因.与可腌制性有关吗?
Perhaps there is some problem in using cv2.cvtColor in MultiProcessing. Someone can shed light on the reasons. Is it about picklability?
这篇关于如何使用多处理并行处理OpenCV的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!