2014-09-05 3 views
1

Я поместил все черные пиксели изображения в массив, и я хочу, чтобы они получили цвет своего левого соседа. Я запускаю код без ошибок, но результат не совсем то, что я ожидаю. Где эти черные полосы появляются? Я ожидал, что все будет красным.Назначить цвет пикселю на основе его соседей

Вот мой код и результаты.

import java.awt.Color; 
import java.awt.image.BufferedImage; 
import java.util.*; 


public class ImageTest { 
    public static BufferedImage Threshold(BufferedImage img) { 

     int height = img.getHeight(); 
     int width = img.getWidth(); 
     BufferedImage finalImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); 

     int r = 0; 
     int g = 0; 
     int b = 0; 
     List<Integer> blackpixels = new ArrayList<Integer>(); 



     for (int x = 0; x < width; x++) { 
      try { 

       for (int y = 0; y < height; y++) { 

        //Get RGB values of pixels 
        int rgb = img.getRGB(x, y); 
        r = ImageTest.getRed(rgb); 
        g = ImageTest.getGreen(rgb); 
        b = ImageTest.getBlue(rgb); 

        int leftLoc = (x-1) + y*width; 

        if ((r < 5) && (g < 5) && (b < 5)) { 
         blackpixels.add(rgb); 
         Integer[] simpleArray = new Integer[ blackpixels.size() ]; 
         System.out.print(simpleArray.length); 

         int pix = 0; 

         while(pix < simpleArray.length) { 
          r = leftLoc; 
          pix = pix +1; 
         } 


        } 

        finalImage.setRGB(x,y,ImageTest.mixColor(r, g,b)); 
       } 

       } 
      catch (Exception e) { 
        e.getMessage(); 
      } 
    } 
    return finalImage; 

    } 
    private static int mixColor(int red, int g, int b) { 
     return red<<16|g<<8|b; 
    } 

    public static int getRed(int rgb) { 
     return (rgb & 0x00ff0000) >> 16; 
    } 

    public static int getGreen(int rgb) { 
     return (rgb & 0x0000ff00) >> 8; 
    } 

    public static int getBlue(int rgb) { 
     return (rgb & 0x000000ff) >> 0; 

    } 
} 

enter image description here

+0

У вас есть время цикла, которая изменяет 'r' значение, может ли это быть причиной полосы? (затухание от черного до красного). – munyul

+0

Да, конечно, но я не могу понять, как заставить его работать так, как я хочу – leonardo

+0

Что именно вы пытаетесь сделать? Каков ожидаемый результат? Не могли бы вы предоставить желаемое изображение? –

ответ

1

Следующая может работать. Главное изменение состоит в том, что он сначала собирает местоположения ВСЕХ темных пикселей, затем перебирает их, чтобы назначить цвет из их левых соседей.

import java.awt.image.BufferedImage; 
import java.util.*; 

public class BlackRedImage 
{ 
    public static BufferedImage Threshold(BufferedImage img) 
    { 
     int height = img.getHeight(); 
     int width = img.getWidth(); 
     BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 

     List<Integer> blackpixels = new ArrayList<Integer>(); 

     for (int x = 0; x < width; x++) 
     { 
      for (int y = 0; y < height; y++) 
      { 
       int rgb = img.getRGB(x, y); // Get the pixel in question 
       int r = BlackRedImage.getRed(rgb); 
       int g = BlackRedImage.getGreen(rgb); 
       int b = BlackRedImage.getBlue(rgb); 

       if ((r < 5) && (g < 5) && (b < 5)) 
       { // record location of any "black" pixels found 
        blackpixels.add(x + (y * width)); 
       } 

       finalImage.setRGB(x, y, rgb); 
      } 
     } 

     // Now loop through all "black" pixels, setting them to the colour found to their left 
     for (int blackPixelLocation: blackpixels) 
     { 
      if (blackPixelLocation % width == 0) 
      { // these pixels are on the left most edge, therefore they do not have a left neighbour! 
       continue; 
      } 

      int y = blackPixelLocation/width; 
      int x = blackPixelLocation - (width * y); 

      int rgb = img.getRGB(x - 1, y); // Get the pixel to the left of the "black" pixel 
      System.out.println("x = " + x + ", y = " + y + ", rgb = " + rgb); 
      finalImage.setRGB(x, y, rgb); 
     } 
     return finalImage; 
    } 

    private static int mixColor(int red, int g, int b) 
    { 
     return red << 16 | g << 8 | b; 
    } 

    public static int getRed(int rgb) 
    { 
     return (rgb & 0x00ff0000) >> 16; 
    } 

    public static int getGreen(int rgb) 
    { 
     return (rgb & 0x0000ff00) >> 8; 
    } 

    public static int getBlue(int rgb) 
    { 
     return (rgb & 0x000000ff) >> 0; 
    } 
} 

EDIT: Вот упрощенная версия (не собирает черных пикселей)

import java.awt.Color; 
import java.awt.image.BufferedImage; 
import java.util.*; 

public class ColourMove 
{ 
    public static BufferedImage Threshold(BufferedImage img) 
    { 
     int width = img.getWidth(); 
     int height = img.getHeight(); 
     BufferedImage finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); 

     for (int x = 1; x < width; x++) // Start at 1 as the left most edge doesn't have a left neighbour 
     { 
      for (int y = 0; y < height; y++) 
      { 
       Color colour = new Color(img.getRGB(x, y)); 
       int red = colour.getRed(); 
       int green = colour.getGreen(); 
       int blue = colour.getBlue(); 

       if ((red < 5) && (green < 5) && (blue < 5)) 
       { // Encountered a "black" pixel, now replace it with it's left neighbour 
        finalImage.setRGB(x, y, img.getRGB(x - 1, y)); 
       } 
       else 
       { // Non-black pixel 
        finalImage.setRGB(x, y, colour.getRGB()); 
       } 
      } 
     } 
     return finalImage; 
    } 
} 
+0

Я получаю сообщение об ошибке «Координация вне границ!», Попытайтесь выяснить, где она выходит за пределы диапазона – leonardo

+0

Была логика ошибка в первой версии, которую я опубликовал (что вызвало бы такую ​​ошибку), убедитесь, что вы попробуете последнюю отредактированную версию сейчас - я надеюсь, что она работает;) – munyul

+0

Да, я не получаю ошибку, но окончательное изображение такое же как исходный образ, никаких изменений не происходит ... strange – leonardo

Смежные вопросы