簡體   English   中英

使用Sobel運算符在PPM上的Java中進行邊緣檢測

[英]Edge detection in Java on a PPM using the Sobel Operator

我正在嘗試使用Sobel算子進行邊緣檢測,並且得到了一個奇怪的三重圖像。

圖像以PPM開頭,我將其存儲為Color的多維數組: 原始圖片

我將其轉換為灰度,似乎可以正常工作: 灰度轉換圖像

但是當我嘗試尋找邊緣時,事情就開始了..很奇怪: 發現邊緣?

鑒於代碼是用Java編寫的,因此相當冗長,因此我只包含了轉換功能。 如果合適的話,我會的。

private Color[][] sobelConvert(Color[][] image) {
    Color[][] newPPM = new Color[maxX][maxY];

    for (int y = 0; y < maxY; y++) {
        for (int x = 0; x < maxX; x++) {
            int a = testForColor(x-1, y-1, image);
            int b = testForColor(x-1, y,   image);
            int c = testForColor(x-1, y+1, image);

            int d = testForColor(x, y-1, image);
            int e = testForColor(x, y+1,   image);

            int f = testForColor(x+1, y-1, image);
            int g = testForColor(x+1, y,   image);
            int h = testForColor(x+1, y+1, image);

            int eH = (c + 2*e + h) - (a + 2*d + f);
            int eV = (f + 2*g + h) - (a + 2*b + c);

            int edgyness = (int) Math.sqrt((eH * eH) + (eV * eV));
            if (edgyness > 255) {
                edgyness = 255;
            }
            if (edgyness < 0) {
                edgyness = 0;
            }
            newPPM[x][y] = new Color(edgyness, edgyness, edgyness);
        }
    }
    return newPPM;
}

testForColor()做一些范圍檢查,並在Color對象中返回RGB值之一-這樣我想我就可以算出亮度。

private int testForColor(int x, int y, Color[][] ppm) {
    if (x < 0 || x >= maxX) {
        return 0;
    }

    if (y < 0 || y >= maxY) {
        return 0;
    }

    return ppm[x][y].getGreen();
}

編輯:添加代碼以讀取和寫入PPM:

public Edgeness(String fileName) throws Exception {
    this.fileName = fileName;
    boolean foundDims = false;
    Color c = null;
    int r, g, b;

    String line;

    try {
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        while ((line = br.readLine()) != null) {
            //System.out.println(line);

            // Test if the line has any lenght (ignore empty lines)
            // First line.  We will ignore it.
            // First character is a #.  Ignore it.  (this is bad - should check the whole line.  TODO.)
            if (line.length() > 0 && !line.equals("P3") && !(line.charAt(0) == '#')) {
                // Check for image dimensions.  Only do this once.  I assume regex's take longer
                // than testing a boolean.
                if (!foundDims) {
                    Pattern pImDim = Pattern.compile("(\\d+) (\\d+)");
                    Matcher mImDim = pImDim.matcher(line);
                    if (mImDim.find()) {
                        maxX = Integer.parseInt(mImDim.group(1));
                        maxY = Integer.parseInt(mImDim.group(2));
                        ppm = new Color[maxX][maxY];
                    }
                    foundDims = true;
                }

                // Hmm.  Last capture is kept, the rest are overwritten.  so.. we split instead.
                // https://stackoverflow.com/questions/3537878/how-to-capture-an-arbitrary-number-of-groups-in-javascript-regexp
                String[] rgbVals = line.split(" ");
                if (rgbVals.length % 3 == 0) {
                    for (int i = 0; i < rgbVals.length; i += 3) {
                        r = Integer.parseInt(rgbVals[i]);
                        g = Integer.parseInt(rgbVals[i+1]);
                        b = Integer.parseInt(rgbVals[i+2]);
                        c = new Color(r, g, b);
                        addNextColor(c);
                    }
                }
            }
        }
        br.close();
    } finally {
    }
}
private void addNextColor(Color c) {
    ppm[currentX][currentY] = c;
    currentY++;
    if (currentY >= maxY) {
        currentX++;
        currentY = 0;
    }
}

以及將PPM保存到文件中的功能。 如果加載PPM,則立即調用render(),生成的圖像是精確的副本。 同樣,如果保存灰度圖像,則會得到上面包含的圖像。

private void render(Color[][] image, String fileName) throws IOException {
    ArrayList<String> output = new ArrayList<String>();
    output.add("P3");
    output.add(maxX + " " + maxY);
    output.add("255");

    for (int x = 0; x < maxX; x++) {
        StringBuilder sb = new StringBuilder();
        for (int y = 0; y < maxY; y++) {
            if (image[x][y] != null) {
                sb.append(image[x][y].getRed() + " " + image[x][y].getGreen() + " " + image[x][y].getBlue() + " ");
            } else {
                sb.append("0 0 0 ");
            }
        }
        output.add(sb.toString());
    }

    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    for (String s : output) {
        bw.write(s);
        bw.newLine();
    }
    bw.close();
}

我使用ImageMagik的轉換程序將PPM輸出轉換為PNG。

我在http://blog.saush.com/2011/04/20/edge-detection-with-the-sobel-operator-in-ruby/中找到了用Ruby編寫的實現,當將其改編為Java時,產生的效果相同結果。

FWIW,來自Reddit的每日編程挑戰。

該算法看起來或多或少是正確的,當然似乎不會導致圖像的這種奇怪失真。 當然,檢查此問題的簡單方法是讓此方法返回其輸入,這應該只為您提供灰度圖像。 我至少會嘗試一下,以查明問題的確切位置,或者縮小范圍。

我在家中有一個示例,它可以進行完整的Canny邊緣檢測(其中一個步驟是sobel邊緣檢測),並逐步打印出中間圖像。 如果我下班后仍然遇到麻煩,希望可以從中給您一些提示。

問題出在其他地方-該方法可以正常工作-可能在顯示屏上

嘗試檢查每個階段,方法是保存用

BufferedImage bim=new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
int[] pix=new int[w*h];
for(i=0; i<pix.length; i++) pix[i]=(p[i%w][i/w].getBlue()<<16)|(p[i%w][i/w].getBlue()<<8)|p[i%w][i/w].getBlue()|0xff000000;
bim.setRGB(0, 0, w, h, pix, o, w);

try {
ImageIO.write(bim, "png", new File(path+".png"));
} catch (IOException ex) { ex.printStackTrace(); }

其中p是您的ppm數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM