【问题标题】:Computing Histogram of an gray scale Image计算灰度图像的直方图
【发布时间】:2021-06-01 10:16:08
【问题描述】:

我被要求在下面创建一个函数来计算任何灰度图像的直方图。我做了很多研究,并在下面收集了这段代码。它运作良好。 然而,我并没有完全理解这段代码背后的逻辑。更具体一点;

  1. 我用histogram = np.zeros([256], np.int32) 行创建了什么样的数组? np.int32 到底是做什么的?
  2. 在下面的 for 循环中,我有点理解,但我对它的工作方式不太了解,清楚地解释这个循环的工作原理会很有帮助。

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

【问题讨论】:

    标签: python numpy loops image-processing histogram


    【解决方案1】:

    我在代码中添加了额外的 cmets 来尝试解释每一行的作用。

    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
    

    【讨论】:

      【解决方案2】:
      1. 根据NumPy documentationnp.int32 是一种表示带符号的 32 位整数的数据类型。因此,它可以存储 [-2147483648; 范围内的任何值; 2147483647]。使用histogram = np.zeros([256], np.int32) 行,您将创建一个包含 256 个此类整数的数组并将它们初始化为零。将位置k 中的整数视为图像中值k 出现次数的计数器。数组的大小为 256,因为一个常见的假设是使用 8 位图像,,每个像素可以取 2^8 = 256 个值之一。
      2. 在 for 循环中,您将遍历图像的所有像素。对于每个像素,您可以使用img[i, j] 获取其值;假设它是v,与0 <= v < 256。然后使用指令histogram[k] += 1 将值等于k 的像素数增加1 个单位。

      【讨论】:

        猜你喜欢
        • 2023-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-24
        • 2019-04-01
        • 2014-04-05
        相关资源
        最近更新 更多