Reputation: 77
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;
histogram = np.zeros([256], np.int32)
line? What does np.int32
do exactly?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
Reputation: 295
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.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
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