I do not understand the code for loading an image in java
I'm working with OpenCV in java, but I don't understand the part of the class that loads images in java:
public class ImageProcessor {
public BufferedImage toBufferedImage(Mat matrix){
int type = BufferedImage.TYPE_BYTE_GRAY;
if ( matrix.channels() > 1 ) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = matrix.channels()*matrix.cols()*matrix.rows();
byte [] buffer = new byte[bufferSize];
matrix.get(0,0,buffer); // get all the pixels
BufferedImage image = new BufferedImage(matrix.cols(),matrix.rows(),type);
final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(buffer, 0, targetPixels, 0, buffer.length);
return image;
}
The main class sends an object to Mat
this class.
The result is sending BufferedImage
, but I don't understand targetPixels because this class doesn't use it somewhere else. But whenever I comment out targetPixels and System.arraycopy, the result shows a black image.
I want to know what targetPixels
- and what is he doing?
source to share
The point is less about this array, but about the methods you'll find there.
You start here: getRaster () . This should return a WritableRaster ... etc.
This class uses getDataBuffer () from the Raster class; and we find:
A class that represents a rectangular array of pixels. The raster encapsulates a DataBuffer that stores samples and a SampleModel that describe how to find a given sample value in the DataBuffer.
What is essentially happening here: this Image object has an array of bytes at the end that should contain certain information.
This is the assignment:
final byte[] targetPixels = ...
retrieves a link for this internal data; and then arrayCopy()
used to copy data into that array.
For the record: this doesn't sound like a good approach - as it only works when this copy action actually affects the internals of that Image. But what if this last call getData()
would create a copy of the internal data?
In other words: this code tries to get direct access to the internal data of some object; and then manipulate that internal data.
Even if it works today, it is not reliable; and may break easily in the future. Another thing: note that this code performs an unconditional listing (DataBufferByte)
. This code throws a RuntimeException if the buffer is not of this type.
Perhaps this is "all is well"; as it all has to do with the "AWT" classes that probably have been around for centuries; and will not change anymore. But as said; this code has various potential problems.
source to share