subtracting RGB values from an Image in Python

Viewed 5696

I'm working in a project where I need to subtract the RGB values from an Image. In example I want to subtract the BLUE channel from RED, so RED gets the difference value of the subtraction.

I have the next properties of the image:
Dimension:1456x2592, bpp:3

The image I'm using gives me the following arrays:

 [[[ 63  58  60]
     [ 63  58  60]
     [ 64  59  61]
      ...,  
     [155 155 161]  
     [155 155 161] 
     [155 155 161]]

     [[ 58  53  55]
      [ 60  55  57]
      [ 62  57  59]
       ...,  
      [157 157 163]
      [157 157 163]
      [158 158 164]]

I know those are the values(RGB) from the image, so now I move on to do the code (I based on this code)

import cv2
import numpy as np
from PIL import Image 

# read image into matrix.
m =  cv2.imread("ITESO.jpeg")


# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
# BLUE = 0, GREEN = 1, RED = 2.    

for py in range(0,h):
    for px in range(0,w):
        #m[py][px][2] = 2   
        n = m[py][px][2]                //n takes the value of RED
        Y = [n, 0, 0]                   //I create an array with [RED, 0, 0]
        m, Y = np.array(m), np.array(Y) 
        m =  np.absolute(m - Y)       //Get the matriz with the substraction 


y = 1
x = 1
print (m)
print (m[x][y]) 

#display image
#cv2.imshow('matrix', m)
#cv2.waitKey(0)
cv2.imwrite('new.jpeg',m)
img = Image.open('new.jpeg')
img.show()

img = Image.open('new.jpeg').convert('L')
img.save('new_gray_scale.jpg')
img.show()

When I print the J matrix it gives the following arrays:

B,G,R

Blue = BLUE - RED

[[[  3  58  60]
  [  3  58  60] 
  [  4  59  61]
  ...,  
 [ 95 155 161]
 [ 95 155 161] 
 [ 95 155 161]]

[[  2  53  55] 
 [  0  55  57]
 [  2  57  59]
 ...,  
 [ 97 157 163] 
 [ 97 157 163] 
 [ 98 158 164]]

But I'm not able to open the new image and if I set one RGB channel to one value it shows me the image. I use the next lines for that:

import cv2
import numpy as np

# read image into matrix.
m =  cv2.imread("python.png")

# get image properties.
h,w,bpp = np.shape(m)

# iterate over the entire image.
for py in range(0,h):
    for px in range(0,w):
        m[py][px][0] = 0 //setting channel Blue to values of 0

# display image
cv2.imshow('matrix', m)
cv2.waitKey(0) 

How can I subtract the RGB channels from each other?

PS: In MatLab it works like a charm, but I'm not able to do it in python.

2 Answers
Related