(Python) make img's close range of RGB/HSV in particular value

Question:

share pic link: https://imgur.com/a/yyQChWQ

If I have black gradient img , we know the RGB is (0 ~ 255) or HSV is (0 ~ 255)

How can I make close color range color together
such as ( 0 ~ 80), ( 80 ~ 160) , ( 160 ~ 255)

  • expect output:
    1. I want the output to be (expect pic in link) (to remove noise)
    2. generate histogram for (original pic) in 1D not 3D that too complicate I can’t understand

here is the .py script can show HSV and RGB of pic, I saved the result in share pic link

import numpy as np
import cv2 
import matplotlib.pyplot as plt

def show_img(path):

    img = cv2.imread(path)
    b, g, r = img[:,:,0], img[:,:,1], img[:,:,2]
    hist_b = cv2.calcHist([b],[0],None,[256],[0,256])
    hist_g = cv2.calcHist([g],[0],None,[256],[0,256])
    hist_r = cv2.calcHist([r],[0],None,[256],[0,256])
    plt.plot(hist_r, color='r', label="r")
    plt.plot(hist_g, color='g', label="g")
    plt.plot(hist_b, color='b', label="b")
    plt.legend()
    plt.show() 
    img2 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    h, s, v = img2[:,:,0], img2[:,:,1], img2[:,:,2]
    hist_h = cv2.calcHist([h],[0],None,[256],[0,256])
    hist_s = cv2.calcHist([s],[0],None,[256],[0,256])
    hist_v = cv2.calcHist([v],[0],None,[256],[0,256])
    plt.plot(hist_h, color='r', label="h")
    plt.plot(hist_s, color='g', label="s")
    plt.plot(hist_v, color='b', label="v")
    plt.legend()
    plt.show()
    
    return hist_r,hist_g, hist_b, hist_h, hist_s, hist_v


aaa =  "/home/student_DC/desktop/optimization_11_10/output_11_10__002/22.png"
r,g,b,h,s,v = show_img(aaa)
Asked By: DC con

||

Answers:

My suggestion is to use a grayscale image so that all the computations and displays are easier:

import numpy as np
import cv2 
import matplotlib.pyplot as plt

path = "**/RKqsXEv.png"

# Read the image in grayscale
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img_filtered = img.copy()

# Simple editing through a loop on pixels value
for i in range (img.shape[0]):
    for j in range(img.shape[1]):
        if (img[i,j] < 80):
            img_filtered[i,j] = 40
        elif (img[i,j] < 160):
            img_filtered[i,j] = 120
        else:
            img_filtered[i,j] = 200

plt.imshow(img_filtered, cmap='gray')
plt.show()

# Calculate a 1D histogram on the grayscale image
hist = cv2.calcHist(img, [0], None, [255], [0,255])
plt.plot(hist)
plt.show()

Output:

enter image description here

enter image description here

Answered By: César Debeunne