A.Papuccu
A.Papuccu

Reputation: 77

Computing Histogram of an gray scale Image

I am asked to create a function below to calculate histogram of any gray-scale image. I did quite a lot research and get together this code below. It is working well. However, I did not understand the logic behind this code exactly. To be more specific;

  1. What kind of a array I created with histogram = np.zeros([256], np.int32) line? What does np.int32 do exactly?
  2. In the for loop below I sort of understand but I am not feeling well understood about the way it works, clear explanation how this loop works would be a big help.

ps: I am not an native-english speaker/writer if any rudeness or informal terms exist in my question, sorry for that!

def calcHistogram(img):
    
    # calculate histogram here
    img_height = img.shape[0]
    img_width = img.shape[1]
    histogram = np.zeros([256], np.int32) 
    
    for i in range(0, img_height):
        for j in range(0, img_width):
            histogram[img[i, j]] +=1
         
    return histogram

Upvotes: 1

Views: 1683

Answers (2)

simonet
simonet

Reputation: 295

  1. According to NumPy documentation np.int32 is a data type that represents a signed, 32-bit, integer. It can therfore store any value in the range [-2147483648; 2147483647]. With line histogram = np.zeros([256], np.int32) you are creating an array of 256 of such integers and initializing them to zero. Think to the integer in position k as the counter of occurrencies of value k in image. The size of the array is 256 because a common assumption is to work with 8-bit images, i.e., every pixel can take one of 2^8 = 256 values.
  2. In the for cycle you are looping through all pixels of the image. For every pixel, you take its value with img[i, j]; suppose it is v, with 0 <= v < 256. Then with the instruction histogram[k] += 1 you are incrementing by 1 unit the number of pixels that have value equal to k.

Upvotes: 1

Ian Chu
Ian Chu

Reputation: 3143

I've added extra comments to the code to try and explain what each line is doing.

def calcHistogram(img):   
    # get image dimensions so that we can loop over the entire image
    img_height = img.shape[0]
    img_width = img.shape[1]

    # initialize an array of 256 ints (all zero)
    # the index range for this list is [0, 255]
    histogram = np.zeros([256], np.int32) 
    
    # loop through each pixel in image
    for y in range(0, img_height):
        for x in range(0, img_width):
            # img[y,x] is the same as img[y][x]
            # it returns the grayscale value of the pixel at that position 
            # (which ranges from [0, 255])
            # we then use that grayscale value as the index for our histogram
            # and add one to that index
            # so histogram[0] represents the number of pixels with a grayscale value of 0
            histogram[img[y, x]] +=1
         
    return histogram

Upvotes: 3

Related Questions