Search code examples
pythonnumpyeditorrgbphoto

Python color adjuster 3d numpy only


I'm trying to make an rgb color picture editor, using just numpy. I've tried using a nested for loop, but it's really slow (over a minute). I'm wanting to control first, second, and third element (r,g,b) of the third dimension of the nested array. Thanks

This is to just look at the numbers:

%matplotlib inline
import numpy as np

img = plt.imread('galaxy.jpg')
img = np.array(img)

for i in range(len(img)):
   for j in range(len(img[i])):
       for k in (img[i][j]):
           print(k)

Solution

  • Perhaps this might help you. np.ndenumerate() lets you iterate through a matrix without nested for loops. I did a quick test and my second for loop (in the example below) is slightly faster than your triple nested for loop, as far as printing is concerned. Printing is very slow so taking out the print statements might help with speed. As far as modifying these values, I added r g b a variables that can be modified to scale the various pixel values. Just a thought, but perhaps it might give you more ideas to expand on. Also, I didn't check to see which index values correspond to r, g, b, or a.

    r = 1.0
    g = 1.0
    b = 1.0
    a = 1.0
    
    for index, pixel in np.ndenumerate(img): # <--- Acheives the same as your original code
        print(pixel) 
    
    for index, pixel in np.ndenumerate(img):
        i = index[0]
        j = index[1]
        print("{} {} {} {}".format(img[i][j][0], img[i][j][1], img[i][j][2], img[i][j][3]))
    
    for index, pixel in np.ndenumerate(img):
        i = index[0]
        j = index[1]
        imgp[i][j][0] *= r;
        imgp[i][j][1] *= g;
        imgp[i][j][2] *= b;
        imgp[i][j][3] *= a;
    

    Hope this helps