0

Supposing I have to run this code for 500.000.000 pixels.

import cv2

path_of_the_picture = "photo.jpg"

picture = cv2.imread(path_of_the_picture, cv2.IMREAD_UNCHANGED) 

number_of_rows,number_of_cols = picture.shape

for x in range(number_of_rows):
    for y in range(number_of_cols):
        picture[x,y] = picture[x,y] + 10

It takes around 30min to complete! Ok, maybe it needs some editing to run, but you get the idea. How can I accelerate the above code with multithreaded code in python? Moreover, can I use some GPU-CUDA power? After searching I found this suggestion: How to Multi-thread an Operation Within a Loop in Python but it does not work for my situation...

1
  • 1
    what is the actual opperation ? it's hard to know which solution adapts better to your problem without knowing the actual problem... here, you could convert image to numpy array and then add 10: picture = np.array(picture) + 10 and i'm sure this is fast enough Commented Jun 27, 2022 at 15:16

1 Answer 1

1

Here you could use numba to speed up the solution. But I think that not knowing you exact problem is hard to estimate best solution:


import numba as nb
import numpy as np
from time import time

n=22400 #aproximately 5e8 pixels
a =np.random.randint(0,255,(n,n),dtype=np.uint8)

def func1(a):
    n=len(a)
    for x in range(n):
        for y in range(n):
            a[x,y] = a[x,y]+10
    return a

@nb.jit
def func2(a):
    n=len(a)
    for x in range(n):
        for y in range(n):
            a[x,y] = a[x,y]+10
    return a


t0 = time()
q1 = func1(a)
t1 = time()
q2 = func2(a)
t2 = time()
q3 = a+10
t3 = time()
print("func1 takes: ", t1-t0)
print("func2 takes: ", t2-t1)
print("numpy takes: ", t3-t2)

Results:

#wich outputs in seconds:
#func1 takes:  1008.4661099910736
#func2 takes:  0.15050935745239258
#numpy takes:  0.1150052547454834
Sign up to request clarification or add additional context in comments.

4 Comments

Here: a =np.random.randint(0,255,(n,n),dtype=np.uint8) how do I write it, since I know rows and columns so that I do not need random?
here a is an example matrix just to run the code... because I DON'T HAVE THE ORIGINAL FILE TO WORK, it was not proportioned in the post. so I invented one "image". just add the @nb.jit to your original code...
So, there is no need to use numpy ?
no, just numba, or you can use numpy to solution 3 (transform to array and add 10) there use picture = np.array(picture )+10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.