「C# 二値化した画像をGraphicsで扱えるようにする」で二値化した画像に、赤枠をつけたりしたいと思って、Graphicsで処理しようとすると、「グラフィック オブジェクトをインデックス付きピクセル形式を持つイメージから作成できません」と怒られます。
void test()
{
//元の画像を読込
OpenCvSharp.IplImage img = new OpenCvSharp.IplImage("test.jpg");
//二値化画像を保存するIplImageの準備
OpenCvSharp.IplImage bin_iplImg = new OpenCvSharp.IplImage(img.Width, img.Height, BitDepth.U8, 1);
//閾値
int threshould = 180;
//グレースケールに変換
img.CvtColor(bin_iplImg, OpenCvSharp.ColorConversion.BgrToGray);
//二値化処理
OpenCvSharp.Cv.Threshold(bin_iplImg, bin_iplImg, threshould, 255, OpenCvSharp.ThresholdType.Binary);
//Bitmapを取得
Bitmap bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(img);
//ここで、「グラフィック オブジェクトをインデックス付きピクセル形式を持つイメージから作成できません」と怒られる
Graphics g = Graphics.FromImage(bmp);
//赤線で囲む
Pen pen = new Pen(Color.FromArgb(150, Color.Red), 10);
g.DrawRectangle(pen, 0, 0, bmp.Width, bmp.Height);
g.Dispose();
pen.Dispose();
pictureBox_scanData.Image = bmp;
}
どうやら、二値化した画像は、Format1bppIndexedなのでダメということのようで。
https://msdn.microsoft.com/ja-jp/library/system.drawing.graphics.fromimage(v=vs.110).aspx
じゃ、どうするか考えたのですが、GetThumbnailImageを使えば、さくっと解決できます。
void test()
{
//元の画像を読込
OpenCvSharp.IplImage img = new OpenCvSharp.IplImage("test.jpg");
//二値化画像を保存するIplImageの準備
OpenCvSharp.IplImage bin_iplImg = new OpenCvSharp.IplImage(img.Width, img.Height, BitDepth.U8, 1);
//閾値
int threshould = 180;
//グレースケールに変換
img.CvtColor(bin_iplImg, OpenCvSharp.ColorConversion.BgrToGray);
//二値化処理
OpenCvSharp.Cv.Threshold(bin_iplImg, bin_iplImg, threshould, 255, OpenCvSharp.ThresholdType.Binary);
//Bitmapを取得
Bitmap bmp = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(img);
//GetThumbnailImageを利用して変換
Image image = bmp.GetThumbnailImage(bmp.Width, bmp.Height, new Image.GetThumbnailImageAbort(dummy), IntPtr.Zero);
//GetThumbnailImageをつかって変換しておけば大丈夫
Graphics g = Graphics.FromImage(image);
//赤線で囲む
Pen pen = new Pen(Color.FromArgb(150, Color.Red), 10);
g.DrawRectangle(pen, 0, 0, bmp.Width, bmp.Height);
g.Dispose();
pen.Dispose();
pictureBox_scanData.Image = bmp;
}