[英]Computing Histogram of an gray scale Image
I am asked to create a function below to calculate histogram of any gray-scale image.我被要求在下面创建一个 function 来计算任何灰度图像的直方图。 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?histogram = np.zeros([256], np.int32)
行创建了什么样的数组? What does np.int32
do exactly? np.int32
究竟做了什么? ps: I am not an native-english speaker/writer if any rudeness or informal terms exist in my question, sorry for that! ps:如果我的问题中存在任何粗鲁或非正式用语,我不是以英语为母语的演讲者/作家,对此深表歉意!
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
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
np.int32
is a data type that represents a signed, 32-bit, integer.np.int32
是一种数据类型,表示带符号的 32 位 integer。 It can therfore store any value in the range [-2147483648;histogram = np.zeros([256], np.int32)
you are creating an array of 256 of such integers and initializing them to zero.histogram = np.zeros([256], np.int32)
您正在创建一个包含 256 个此类整数的数组并将它们初始化为零。 Think to the integer in position k
as the counter of occurrencies of value k in image .k
中的 integer 视为 image 中 k值出现的计数器。 The size of the array is 256 because a common assumption is to work with 8-bit images, ie , every pixel can take one of 2^8 = 256 values.img[i, j]
;img[i, j]
获取其值; suppose it is v
, with 0 <= v < 256
.v
,其中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
.histogram[k] += 1
将值等于k
的像素数增加 1 个单位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.