Search code examples
pythonnumpyloopsimage-processinghistogram

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

Solution

    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.