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...

just_learning
  • 413
  • 2
  • 11
  • 24
  • 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 – Ulises Bussi Jun 27 '22 at 15:16

1 Answers1

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
Ulises Bussi
  • 1,635
  • 1
  • 2
  • 14
  • 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? – just_learning Jun 27 '22 at 16:36
  • 1
    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... – Ulises Bussi Jun 27 '22 at 16:43
  • So, there is no need to use ```numpy``` ? – just_learning Jun 27 '22 at 16:48
  • 1
    no, just numba, or you can use numpy to solution 3 (transform to array and add 10) there use `picture = np.array(picture )+10` – Ulises Bussi Jun 27 '22 at 17:02