SA-Kenan/04_Spurerkennung/dev/dev_grayscale_conversion.py
2022-05-09 20:30:26 +02:00

55 lines
1.7 KiB
Python

# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 17:08:00 2022
@author: Kenan
"""
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
path = r"U:\images_input\image.png"
def convert_rgb_to_grayscale_average(image_b, image_g, image_r):
"""This function converts the RGB image into an grayscale image.
Algorithm: Average: Y = (R+G+B)/3"""
image_r = image_r.astype(np.uint16) #sporadische lösung. umwandlung vor addition, damit keine gehler weil uint8 --> overflow
image_g = image_g.astype(np.uint16)
image_b = image_b.astype(np.uint16)
image_gray = (image_b+image_g+image_r)/3
image_gray = image_gray.astype(np.uint8)
return image_gray
def convert_rgb_to_grayscale_average_v2(image_b, image_g, image_r):
"""This function converts the RGB image into an grayscale image.
Algorithm: Average: Y = (R+G+B)/3"""
image_gray = 1/3*image_r + 1/3*image_g + 1/3*image_b # automatically converts into float64
image_gray = image_gray.astype(np.uint8)
return image_gray
image_bgr = cv.imread(path, cv.IMREAD_COLOR) # load original image
image_b,image_g,image_r = cv.split(image_bgr) # Split colour channels and get grayscale images
image_grayscale_avg = convert_rgb_to_grayscale_average(image_b, image_g, image_r)
plt.imshow(image_grayscale_avg, cmap = 'gray')
image_grayscale_avg_v2 = convert_rgb_to_grayscale_average_v2(image_b, image_g, image_r) # new alrorithm, cleaner
# Test if both are same
res = np.all(image_grayscale_avg_v2==image_grayscale_avg)
print(res) # False
# Explanation:
# row = 227, col = 7 : r=2, g=10, b=0
# opt1: (r+g+b)/3 = 12/3 = 4 -->int = 4
# v2: 1/3*2 +1/3*10 + 1/3*0 = 0.6666+3.3333 = 3.9999 -->int = 3 --> FALSE
# conclusion: opt 1 is better