Pixels da imagem para matriz 4x4[resolvido]

10 respostas
B

pessoal qro jogar uma imagem para uma matriz tenhos esses metodos quem pegam a imagem e modifica seus pixels, para imagem ficar cinza, ai queria pegar ela e dividir em uma matriz [4][4]os seus pixels pra executar outros calculos. caso alguem queira saber o pq disso preciso implementar pra facu o filtro passa alta. caso alguem ja tenha feito tbm da um help ai vlw

public void obtemImagem(File f) throws Exception {  
              
            imagem = ImageIO.read(f); //ImagemIO é um método estático  
            int w = imagem.getWidth();  
            int h = imagem.getHeight();  
            pixels = imagem.getRGB(0, 0, w, h, null, 0, w);  
           
        }  
            
        public int obtemIntensidade(int indice){  
              
            Color c = new Color(pixels [indice]);  
            return(int) (0.3*c.getRed()+0.59*c.getGreen()+0.11*c.getBlue());  
        }  
         
        public void converteTonsDeCinza(){  
            int intensidade;  
            int w = imagem.getWidth();  
            int h = imagem.getHeight();  
              
            for (int i = 0; i < pixels.length; i++) {  
                intensidade = this.obtemIntensidade(i);  
                pixels[i] = new Color(intensidade,intensidade,intensidade).getRGB();  
            }  
              
            imagem.setRGB(0, 0, w,h,pixels,0,w);  
        }

10 Respostas

V

Certo… e a dúvida qual é mesmo?

B

apos executar o metodo converteTonsDeCinza(); qro pegar a imagens e dividir em uma matriz [4][4] recebendo os pixels da referente posicao tipo

[0][0] = 39844
:
:
:

V

Não é 3x3? Normalmente nós fazemos processamento de imagens com matrizes em que o pixel sendo processado esteja no centro (3x3, 5x5).
Se quiser aplicar algo diferente disso, também vai ter que especificar qual é o pixel central.

Mas enfim, para uma matriz 3x3, o calculo é bastante simples:

for (int py = 0; py &lt; imagem.getHeight(); py++)
    for (int px = 0; px &lt; imagem.getWidth(); px++) {
        int minX = Math.max(0, px-1);
        int maxX = Math.min(px+1, imagem.getWidth());

        int minY = Math.max(0, py-1);
        int maxY = Math.min(py+1, imagem.getHeight());

        for (int y = minY; x &lt; maxY; y++) {
            for (int x = minX; x &lt; maxX; x++) {
                //Aqui dentro, os pixels da matriz 3x3 serão representados por imagem.getRGB(x,y);
                //E o pixel central por imagem.getRGB(px, py);
            }
        }
    }
}
B

fiz assim mais deu erro poderia me ajudar!!

java.lang.ArrayIndexOutOfBoundsException: 30876

public void montarMatriz() {
       // int array[]= new int[pixels.length];
        result = new double[pixels.length];
        System.out.println("tamanho:"+pixels.length);
        int indice = 0;
        
          for (int h = 0; h < imagem.getHeight(); h++) {
              for (int w = 0; w < imagem.getWidth(); w++) {
                  indice = w + (w*h);
                  
                  if(w == 9){
                      int i = 0;
                      System.out.println( i+ "vezes");
                      i++;
                  }
                  
                if (h == 0 || w == 0 || h == imagem.getHeight()
                        || w == imagem.getWidth() ) {
                   //  array[indice] = pixels[indice];
                     result[indice] = pixels[indice];
                     
                     System.out.println("Borda -valor:"+pixels[indice]+"-indice:"+indice);

                }else {
                     filtro =  ((pixels[w-1+(w*(h-1))]*f[0][0])*obtemVermelho(indice))+
                               ((pixels[w+(w*(h-1))]*f[0][1])*obtemVermelho(indice))+
                               ((pixels[w+1+(w*(h-1))]*f[0][2])*obtemVermelho(indice))+
                               ((pixels[w-1+(w*(h))]*f[1][0])*obtemVermelho(indice))+
                               ((pixels[w+(w*(w*(h)))]*f[1][1])*obtemVermelho(indice))+
                               ((pixels[w+1+(w*(w*(h)))]*f[1][2])*obtemVermelho(indice))+
                               ((pixels[w-1+(w*(w*(h)))]*f[2][0])*obtemVermelho(indice))+
                               ((pixels[w+(w*(w*(h+1)))]*f[2][1])*obtemVermelho(indice))+
                               ((pixels[w+1+(w*(w*(h+1)))]*f[2][2])*obtemVermelho(indice)); 
                     
                     System.out.print("valor:"+filtro);
                     result[indice] = filtro;
                     System.out.println("Filtro:"+filtro+"- indice:"+indice);
                     
                }
                  
              }
          }
    }
V

Por que não usa o código que te passei? Ele já trata isso…

B

sinceramente por ter ficar bitolado nakilo to com dificuldade no else , nao to sabendo aplicar a regra que fiz no outro nele

for (int py = 0; py < imagem.getHeight(); py++) {
            for (int px = 0; px < imagem.getWidth(); px++) {
                int minX = Math.max(0, px - 1);
                int maxX = Math.min(px + 1, imagem.getWidth());

                int minY = Math.max(0, py - 1);
                int maxY = Math.min(py + 1, imagem.getHeight());

                if (py == 0 || px == 0 || py == imagem.getHeight()
                        || px == imagem.getWidth()) {

                    result[indice] = pixels[indice];
                } else {

                    for (int y = minY; y < maxY; y++) {
                        for (int x = minX; x < maxX; x++) {
                            indice = x + (x * y);
                            //Aqui dentro, os pixels da matriz 3x3 serão representados por imagem.getRGB(x,y);  
                            //E o pixel central por imagem.getRGB(px, py);
                            filtro = imagem.

                        }
                    }
                }
            }
        }
V

Como o seu filtro tem que trabalhar?

Que operação ele deve fazer sobre os pixels?

B

entao cara fui tirar a duvida com o pessoal simplesmente tem uma outra matriz por exemplo

private double[][] f = {{0.25 , 0.25 ,0.25},{0.25 , 0.25 , 0.25},{0.25 , 0.25 , 0.25}};

ai uma multiplicaçao da pixels * essa matriz f

akele codigo q postei esta com a formula correta porem na mao…

estamos tentando fazer isso caso ja tenha feito algo do tipo…

http://www.tecgraf.puc-rio.br/~mgattass/fcg/trb12/Tais%20de%20Sa%20Pereira/

Passa Alta,

temos pronta a tons de cinza a imagem, so q num sei pq nesse estoura

V
Eis um exemplo. Aplica o kernel equivalente ao filtro de sobel. Você pode substituir pelo seu kernel e testar:
package br.com.guj;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;

public class Filter {
	public static int saturate(int color)
	{
		if (color &lt; 0) return 0;
		if (color &gt; 255) return 255;
		return color;
	}
	public static int pad(int coord, int max)
	{
		if (coord &lt; 0) return 1;
		if (coord &gt;= max) return max-2;
		return coord;
	}
	
	public static BufferedImage applyFilter(BufferedImage image, double[][] kernel)
	{
		BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
		for (int py = 0; py &lt; image.getHeight(); py++)
		    for (int px = 0; px &lt; image.getWidth(); px++) {
		    	int[] rgb = {0,0,0};
		    	for (int ky = 0; ky &lt; 3; ky++)
		    		for (int kx = 0; kx &lt; 3; kx++)
		    		{
		    			int y = pad(py - ky - 1, image.getHeight());
		    			int x = pad(px - kx - 1, image.getWidth());
		    			rgb[0] += new Color(image.getRGB(x, y)).getRed() * kernel[kx][ky];
		    			rgb[1] += new Color(image.getRGB(x, y)).getGreen() * kernel[kx][ky];
		    			rgb[2] += new Color(image.getRGB(x, y)).getBlue() * kernel[kx][ky];
		    		}
		    	result.setRGB(px, py, new Color(
		    			saturate(rgb[0]), saturate(rgb[1]), saturate(rgb[2])).getRGB());
		    }
		return result;
	}
	
	public static void main(String[] args) throws IOException {
		double[][] sobelEdgeDetector = {
				{-1,  0,  1}, 
				{-2,  0,  2}, 
				{-1,  0,  1}};
		BufferedImage sample = ImageIO.read(Filter.class.getResource(&quot;/br/com/guj/resource/input.png&quot;));
		BufferedImage result = applyFilter(sample, sobelEdgeDetector);
		
		JFileChooser chooser = new JFileChooser();
		chooser.setSelectedFile(new File(&quot;./output.png&quot;));
		if (chooser.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
			return;
		ImageIO.write(result,&quot;png&quot;, chooser.getSelectedFile());
	}
}

O programa aceita um png de entrada, que deve estar no pacote br.com.guj.resource e chamar-se input.png. O programa pedirá para você escolher o local e o nome da imagem de saída.

Um detalhe é que você deve definir como tratar as bordas. No caso desse programa, eu estou pegando o pixel de "reflexo". Quem faz esse tratamento é o método pad.
Eu só considerei kernels de 3x3. Fica a seu critério alterar o programa para considerar kernels maiores (como 5x5 ou 7x7).

B

vlw cara mto obrigado…

Criado 1 de novembro de 2012
Ultima resposta 8 de nov. de 2012
Respostas 10
Participantes 2