2017-09-29 4 views
0

L'image est convertie en niveaux de gris, mais présente trois tuiles à cause du BufferedImage.TYPE_3BYTE_BGR.OpenCV convertissant Mat en image en niveaux de gris

.TYPE_BYTE_GRAY ne fonctionne pas. Comment afficher une seule image en niveaux de gris?

public void matToBufferedImage(Mat matRGB){ 
    Mat mGray = new Mat(); 
    Imgproc.cvtColor(matRGB, mGray, Imgproc.COLOR_BGR2GRAY); 
    int width = mGray.width(), height = mGray.height(), channels = mGray.channels(); 
    byte[] source = new byte[width * height * channels]; 
    mGray.get(0, 0, source); 

    image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); 

    final byte[] target = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); 
    System.arraycopy(source, 0, target, 0, source.length); 
} 

Répondre

0

J'utilise ces deux méthodes pour de tels cas.

public static BufferedImage Mat2BufferedImage(Mat matrix) throws IOException { 
    MatOfByte mob=new MatOfByte(); 
    Imgcodecs.imencode(".jpg", matrix, mob); 
    return ImageIO.read(new ByteArrayInputStream(mob.toArray())); 
} 

public static Mat BufferedImage2Mat(BufferedImage image) throws IOException { 
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
    ImageIO.write(image, "jpg", byteArrayOutputStream); 
    byteArrayOutputStream.flush(); 
    return Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED); 
} 

Ainsi, après l'ajout de ces deux méthodes, vous les utiliser comme,

Imgproc.cvtColor(matRGB, mGray, Imgproc.COLOR_BGR2GRAY); 

image = Mat2BufferedImage(mGray); 
+0

Il est pour la capture vidéo et la reconnaissance. Le code fonctionnerait-il aussi pour cela ou seulement pour les images fixes? –

+0

Une vidéo n'est rien d'autre qu'une collection d'images. Ça va marcher. Pourquoi ne te vois-tu pas? – Ultraviolet