Home>

I want to divide an image with python, find the HSV value for each divided image, and visualize it.
I saw the code of the answer of another answerer (tiitoi) (the code below), but I still get an error and I would like to refer to it, but it is not working.
I'm not sure how to define channels.
There are some points that cannot be reached with the first question, but please teach someone.

import cv2
import matplotlib.pyplot as plt
import numpy as np
def split_imgs (img, hsplits = 3, vsplits = 3):
    h, w = img.shape [: 2]
    crop_img = img [: h // vsplits * vsplits,: w // hsplits * hsplits]
    return np.array (
        [x for h_img in np.vsplit (crop_img, vsplits) for x in np.hsplit (h_img, hsplits)]
    )

def hsv_hist (img):
    # Convert to HSV color space.
    hsv = cv2.cvtColor (img, cv2.COLOR_BGR2HSV)
    #Calculate the histogram for each channel.
    hists = []
    for ch in range (3):
        hist = cv2.calcHist ([hsv], [ch], None, [256], [0, 256])
        hists.append (hist)
    return hists

#Load the image.
hsplits = 3 # number of horizontal divisions
vsplits = 3 # number of vertical divisions
img = cv2.imread ("17.4.png")
#Split the image.
sub_imgs = split_imgs (img, hsplits, vsplits)
print (sub_imgs.shape) # (9, 140, 186, 3)
# Get a histogram of each image.
hists = np.array ([hsv_hist (x) for x in sub_imgs])
print (hists.shape) # (9, 3, 256, 1)
# Draw a histogram.
ch_names = {0: "H", 1: "S", 2: "V"}
fig, axes = plt.subplots (hsplits, vsplits, figsize = (10, 10))
for ax, hsv_hist in zip (axes.ravel (), hists):
# Draw each histogram.
    for hist, [ch] in zip (hsv_hist, channels):
        ax.plot (hist, label = ch_names [ch])
    ax.set_xlim ([0, 256])
    ax.set_xlabel ("Pixel Value")
    ax.legend ()
plt.show ()

As you can see,'channels' is not defined and it doesn't work.

-------------------------------------------------- -------------------------
NameError Traceback (most recent call last)
<ipython-input-38-4513b313dd4e>in<module>
     45 # Draw each histogram.
     46
--->47 for hist, [ch] in zip (hsv_hist, channels):
     48 ax.plot (hist, label = ch_names [ch])
     49 ax.set_xlim ([0, 256])
NameError: name'channels' is not defined
Supplementary information (FW/tool version, etc.)

python 3.7.6