Java & OpenCV 无法将 RGB .gif 图像转换为 GRAY

Java & OpenCV can't convert RGB .gif image to GRAY

我想使用 Java 和 OpenCV 将图片从 RGB 转换为 GRAY

所有扩展图像都正常工作,我拍了灰色图像,

如果我制作 .GIF 图像(不移动),它会给我这个错误:

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cv::cvtColor

java代码:

Mat scrImg = Highgui.imread(path);
Mat dstImg = new Mat(scrImg.rows(),scrImg.cols(),scrImg.type());
Imgproc.cvtColor(scrImg, dstImg, Imgproc.COLOR_RGB2GRAY);

private static BufferedImage Mat2BufferedImage(Mat matrix){
 BufferedImage bimOut;
 int type;
 if(matrix.channels() == 1)
  type = BufferedImage.TYPE_BYTE_GRAY;
  
 else 
  type = BufferedImage.TYPE_3BYTE_BGR;
 
 int dataLength = matrix.channels()*matrix.cols()*matrix.rows();
 byte [] buffer = new byte[dataLength];
 bimOut = new BufferedImage(matrix.cols(),matrix.rows(),type);
 matrix.get(0,0,buffer);
 final byte[] bimPixels = ((DataBufferByte) bimOut.getRaster().getDataBuffer()).getData();
 System.arraycopy(buffer, 0, bimPixels, 0, buffer.length);
 
 return bimOut;

}

据官方报道documentation

Currently, the following file formats are supported:

  • Windows bitmaps - *.bmp, *.dib (always supported)
  • JPEG files - *.jpeg, *.jpg, *.jpe (see the Notes section)
  • JPEG 2000 files - *.jp2 (see the Notes section)
  • Portable Network Graphics - *.png (see the Notes section)
  • WebP - *.webp (see the Notes section)
  • Portable image format - *.pbm, *.pgm, *.ppm *.pxm, *.pnm (always supported)
  • Sun rasters - *.sr, *.ras (always supported)
  • TIFF files - *.tiff, *.tif (see the Notes section)
  • OpenEXR Image files - *.exr (see the Notes section)
  • Radiance HDR - *.hdr, *.pic (always supported)
  • Raster and Vector geospatial data supported by Gdal (see the Notes section)

显然不包括支持因为 gif 是专有格式。 http://answers.opencv.org/question/72134/cv2imread-cannot-read-gifs/