Skip to content

Instantly share code, notes, and snippets.

@AlphaNext
Created December 23, 2019 05:47
Show Gist options
  • Save AlphaNext/20a74d872505a36d514778b9b0719e92 to your computer and use it in GitHub Desktop.
Save AlphaNext/20a74d872505a36d514778b9b0719e92 to your computer and use it in GitHub Desktop.
read GIF image using ImageMagick and convert GIF to OpenCV Mat frames
#include <opencv2/opencv.hpp>
#include <Magick++.h>
#include <iostream>
using namespace std;
using namespace Magick;
using namespace cv;
// imageMagick installation on Mac OSX: https://www.sethvargo.com/install-imagemagick-on-osx-lion/
// read gif's first frame to cv::Mat https://stackoverflow.com/questions/41841553/convert-magickimage-to-cvmat
// ref link: https://imagemagick.org/discourse-server/viewtopic.php?t=35080
// compile: g++ test_gif.cpp `pkg-config --cflags opencv` `pkg-config --libs opencv` `pkg-config --cflags magick++` `pkg-config --libs magick++`
cv::Mat Magick2Mat(Image& image){
// Get dimensions of Magick++ Image
int w = image.columns();
int h = image.rows();
// Make OpenCV Mat of same size with 8-bit and 3 channels
Mat opencvImage(h,w,CV_8UC3);
// Unpack Magick++ pixels into OpenCV Mat structure
image.write(0,0,w,h,"BGR",Magick::CharPixel,opencvImage.data);
return opencvImage;
}
Magick::Image Mat2Magick(Mat& src){
if(src.channels()==4) {
Image mgk(src.cols, src.rows, "BGRA", CharPixel, (char *)src.data);
return mgk;
}
if(src.channels()==3){
cvtColor(src,src,cv::COLOR_BGR2BGRA);
Image mgk(src.cols, src.rows, "BGRA", CharPixel, (char *)src.data);
return mgk;
}
if(src.channels()==1) {
cvtColor(src,src,cv::COLOR_GRAY2BGR);
cvtColor(src,src,cv::COLOR_BGR2BGRA);
Image mgk(src.cols, src.rows, "BGRA", CharPixel, (char *)src.data);
return mgk;
}
}
int main(int argc,char **argv){
// Initialise ImageMagick library
// InitializeMagick(*argv);
InitializeMagick("");
// Create Magick++ Image object and read image file
list<Image> imageList;
readImages(&imageList, "sample.gif");
list<cv::Mat> newList;
for(list<Image>::iterator it = imageList.begin(); it != imageList.end(); it++){
Mat tmp = Magick2Mat(*it);
newList.push_back(tmp);
}
cout << newList.size() << endl;
// writeImages(newList.begin(),newList.end(),"tmp/new_image.miff");
for(list<cv::Mat>::iterator it = newList.begin(); it!=newList.end(); it++){
cv::imshow("GIF", *it);
// cv::waitKey(0);
}
cv::waitKey(0);
cv::destroyAllWindows();
// Save opencvImage
// imwrite("result.png", opencvImage);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment