2015-11-25 46 views
0

這是我的計算機科學課程的一部分。其中一項任務是拍攝照片並反映出來。我已經初始化了一張名爲image的圖片。當我運行這種方法時,不是反映它反映的圖像。反映圖像

public void reflect() 
{ 
    //Creating a for loop to get all of the x values for the image object 
    for(int x = 0; x < image.getWidth(); x++) 
    { 
     //Creating a nested for loop to get all of the y values for each x value 
     for(int y = 0; y < image.getHeight(); y++) 
     { 
      //Getting a pixel object for the given x and y value 
      Pixel pixelObj = image.getPixel(x, y); 
      //I'm pretty sure this next line is where I'm screwing up. 
      //It's probably really simple, but I can't figure it out. 
      Pixel newPixel = image.getPixel(image.getWidth()-x-1, y); 
      //This sets the color values of the new pixel to the ones of the old pixel 
      newPixel.setRed(pixel0bj.getRed()); 
      newPixel.setGreen(pixel0bj.getGreen()); 
      newPixel.setBlue(pixel0bj.getBlue()); 
     } 
    } 
    image.show(); 
} 
+0

歡迎來到SO!確保始終提出問題。我沒有看到任何問號。另外,確保你正確地標記你的問題;這是什麼語言? –

+0

圖像的反映不是它的鏡像嗎?或者你的意思是它是錯誤軸上的鏡像? –

+0

對不起。該語言是Java。問題是如何讓它反射而不是鏡像?我的意思是我想翻轉圖像,而不是圖像的前半部分,然後圖像的前半部分位於軸上。所以如果你有一個字母C的圖像,反射會將它變成一個向後的C,但鏡像它會使O. – LacksCreativity

回答

0

您必須交換相應的像素值。目前,在將其像素值保存在將其放到左半部分的參考中之前,您正在覆蓋圖像的右半部分。

在下面,我說明通過「交換」的價值,而不是僅僅給他們分配單向我的意思:

//Getting a pixel object for the given x and y value 
Pixel pixelObj = image.getPixel(x, y); 
Pixel oppositePixel = image.getPixel(image.getWidth()-x-1, y); 
//Store the RGB values of the opposite pixel temporarily 
int redValue = oppositePixel.getRed(); 
int greenValue = oppositePixel.getGreen(); 
int blueValue = oppositePixel.getBlue(); 
//This swaps the color values of the new pixel to the ones of the old pixel 
oppositePixel.setRed(pixel0bj.getRed()); 
oppositePixel.setGreen(pixel0bj.getGreen()); 
oppositePixel.setBlue(pixel0bj.getBlue()); 
pixelObj.setRed(redValue); 
pixelObj.setGreen(greenValue); 
pixelObj.setBlue(blueValue); 

如果你換的像素在每一輪兩種方式,這是足夠的循環從0image.getWidth()/2

看看它是如何在ImageJ's ImageProcessor class作爲參考。

另一種解決方案是在x方向上使用矩陣變換和-1縮放。請參閱ImageJ scale op以獲得更詳細的示例,使用ImgLib2 library進行Java中的圖像處理。

+0

我改變它image.getWidth()/ 2,但它仍然有同樣的問題。我不明白你鏈接到的兩段代碼,我仍然很初學。你能更具體地說明我應該改變什麼嗎? – LacksCreativity

+0

@Compton我編輯我的答案來說明我的意思是交換。 –