2017年10月18日水曜日

リサイズした画像をcv2.imwriteで保存してみる

以下の手直しを実施
- アスペクトを整える
- リサイズ後のサイズを表示する : textbox4
- 保存ボタン押下で画像をcurrent directoryに保存
- stop watchによる処理時間の目安をdebug出力に表示

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;        // file / directory文字列処理など
using OpenCvSharp;
using OpenCvSharp.Extensions;

using System.Diagnostics;

namespace DragDrop01
{
    public partial class Form1 : Form
    {
        Mat resizedImage;

        public Form1()
        {
            InitializeComponent();
            listBox1.AllowDrop = true;      // プロパティを編集してもよい(やらないとEnterイベントが発生しない模様)

            resizedImage = new Mat();
        }

        private void listBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            } else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void listBox1_DragDrop(object sender, DragEventArgs e)
        {
            string[] fileName = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            listBox1.Items.AddRange(fileName);
        }

        // listboxの選択変更
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string currentItem = listBox1.SelectedItem.ToString();  // アイテムを取得する

            // int index = listBox1.FindString(currentItem);           // (↑のアイテムから)indexを取得する事も可

            textBox1.Text = Path.GetDirectoryName(currentItem);
            textBox2.Text = Path.GetFileName(currentItem);

            Mat image = new Mat(currentItem);

            string imageSize = image.Width.ToString() + " : " + image.Height.ToString();
            textBox3.Text = imageSize.ToString();

            int targetHeight = image.Height * pictureBox1.Width / image.Width;
            textBox4.Text = pictureBox1.Width.ToString() + " : " + targetHeight.ToString();

            Stopwatch sw = new Stopwatch();
            sw.Start();
            Cv2.Resize(image, resizedImage, new OpenCvSharp.Size(pictureBox1.Width, targetHeight));

            Debug.WriteLine(sw.Elapsed);
            pictureBox1.Image = BitmapConverter.ToBitmap(resizedImage);
            Debug.WriteLine(sw.Elapsed);
            sw.Stop();
        }

        // 保存ボタン押下処理
        private void button_save_Click(object sender, EventArgs e)
        {
            // 実行ファイルのcurrent dirに保存してみる
            string currentDir = Directory.GetCurrentDirectory() + "\\" + textBox2.Text;
            Cv2.ImWrite(currentDir, resizedImage);
        }
    }
}

0 件のコメント:

コメントを投稿