简体   繁体   中英

Python RGB to grayscale conversion (ExGG) matrix operation

I am trying to write a function which does conversion from RGB to grayscale image. Values in grayscale image are calculated using ExGG (green extraction) method. Values are calculated as follows:

ExGG = (2 * g - b - r) * g

Where

r = R' / (R' + G' + B'),
g = G' / (R' + G' + B'),
b = B' / (R' + G' + B')

and R', G' and B' are normalized values from an RGB image in range [0, 1].

I have managed to come up with following pixel-wise solution:

    for i in range(rows):
        for j in range(cols):
            (R, G, B) = image[i][j]
            RGB_sum = (R + G + B)
            r = R / RGB_sum
            g = G / RGB_sum
            b = B / RGB_sum
    
            # ExGG
            output[i][j] = ((2 * g) - b - r) * g

Where image is normalized RGB image (dtype is float64).

This element-wise calculation is providing correct result but it seems to be pretty slow, therefore i want to update this function to perform matrix operation instead of element-wise approach. Also, if anyone knows a way to perform these operations faster feel free to share.

This should work.

import numpy as np

img = np.random.rand(4,4,3)
rgb_sum = np.sum(img, axis = 2)
img_rgb = img / rgb_sum[:, :, None]
r = img_rgb[:, :, 0]
g = img_rgb[:, :, 1]
b = img_rgb[:, :, 2]
output = ((2 * g) - b - r) * g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM