在Java中计算中间灰度(max(z)+min(z)/2的图像分析功能



如何在结构元素为1的点上计算中间灰度级(max(z)+min(z)/2并将输出像素设置为该值?

我只知道一点关于如何通过使用image.getRGB(x,y)获得每个像素的RGB值。我不知道如何获得图像的每个像素的灰度值,公式中的z是什么?

请帮我一下。

我将假设z是您的结构元素中的像素。我还将假设"结构元素"是在形态学的情况下。在我们开始之前,这里有一些提示:

  1. 您可以使用亮度公式将颜色像素转换为其灰度强度。通过参考SMPTE Rec. 709标准,给定RGB分量的输出灰度强度为:Y = 0.2126*R + 0.7152*G + 0.0722*B .
  2. 我们假设结构元素是奇数。这将允许对图像中每个像素的结构元素进行对称分析
  3. 我将假设您的图像已经作为BufferedImage加载。
  4. 你的结构元素将是int的2D数组。
  5. 我不打算处理那些像素,其中结构元素遍历超出边界,使事情变得简单。

因此,基本算法是这样的:
  1. 对于图像中的每个像素,将结构元素的中心放置在此位置
  2. 对于与此位置重合的结构元素为1的每个像素位置,找到最大和最小灰度强度
  3. 设置此位置的输出图像像素为(max(z) + min(z)) / 2)

废话少说:

public BufferedImage calculateMiddleGray(BufferedImage img, int[][] mask)
{
    // Declare output image
    BufferedImage outImg = new BufferedImage(img.getWidth(),
            img.getHeight(), BufferedImage.TYPE_INT_RGB);
    // For each pixel in our image...
    for (int i = mask.length/2; i < img.getWidth() - mask.length/2; i++) {
        for (int j = mask[0].length/2; j < img.getHeight() - mask[0].length/2; j++) {
            int maxPix = -1;
            int minPix = 256;
            // For each pixel in the mask...
            for (int x = -mask.length/2; x <= mask.length/2; x++) {
                for (int y = -mask[0].length/2; y <= mask[0].length/2; y++) {
                   //Obtain structuring element pixel
                   int structPix = mask[y+mask.length/2][x+mask[0].length/2];
                   // If not 1, continue
                   if (structPix != 1)
                       continue;                      
                   // Get RGB pixel
                   int rgb = img.getRGB(i+x, j+y);
                   // Get red, green and blue channels individually
                   int redPixel = (rgb >> 16) & 0xFF;
                   int greenPixel = (rgb >> 8) & 0xFF;
                   int bluePixel = rgb & 0xFF;
                   // Convert to grayscale
                   // Performs SMPTE Rec. 709 lum. conversion using integer logic
                   int lum = (77*red + 150*green + 29*blue) >> 8;
                   // Find max and min appropriately
                   if (lum > maxPix)
                       maxPix = lum;
                   if (lum < minPix)
                       minPix = lum;
              }
           }
           // Set output pixel
           // Grayscale image has all of its RGB pixels equal
           int outPixel = (maxPix + minPix) / 2;
           // Cap output - Ensure we don't go out of bounds
           if (outPixel > 255)
               outPixel = 255;
           if (outPixel < 0)
               outPixel = 0;
           int finalOut = (outPixel << 16) | (outPixel << 8) | outPixel;
           outImg.setRGB(i, j, finalOut);
       }
   }
}

要调用这个方法,使用任何标准方法创建一个图像img,然后创建一个结构元素mask,它是一个2D整数数组。之后,将此方法放入类中,然后通过以下方式调用该方法:

BufferedImage outImg = calculateMiddleGray(img, mask);

另外(当然),确保为BufferedImage类导入了必要的包,或者:

import java.awt.image.BufferedImage;

注意:这是未经考验的代码。希望它有效!

最新更新