0

I have a image list. How to use multi thread to process each image.

import cv2

def job(a_img, b_img):  # want to use multi thread
    #  do something    

images = ['1.png', '2.png', '3.png', ..., '100.png']  # images list
out = []

for i in range(len(images) - 1):
    # read image
    img_1 = cv2.imread(images[i])
    img_2 = cv2.imread(images[i + 1])

    res = job(img_1, img_2)
    out.append(res)

Every two image is processed individually.

How to solve?

vincentlai
  • 379
  • 5
  • 18

1 Answers1

0

If you are looking for a performance boost, you should look into multiprocessing as opposed to multi-threading. The threads all work in the single core of your CPU but they halt in between their tasks and let the other thread take over. So only one sequence of instructions are handled at a time yet you get the illusion of multiple tasks happening because of the halting and running of different threads.

As to answer your question by giving out a trimmed down super short example, the python docs themselves have some pretty great examples, but this would suffice:

Make a function which accepts an image and processes upon it say target_func and then use multi threading as follows:

if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=target_func, args=(your_image_over_here,))
t2 = threading.Thread(target=target_func, args=(your_second_image_over_here,))

# starting thread 1
t1.start()
# starting thread 2
t2.start()

# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()

# both threads completely executed
print("Done!")

# Or alternatively use a for loop to iterate through your image list and pass each item of the list element as the argument to the function creating a list of threads.
# Iterate through the list of of threads calling t[i].start() and so on ...
Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29
  • but I want get result of two image – vincentlai Jul 16 '18 at 03:54
  • you tried going through the python docs? or probably a good tutorial on multithreading or multi processing? as I said that was the shortest eg to get you started. here's what you are looking for https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python – Ishan Srivastava Jul 16 '18 at 03:59