shimat / opencvsharp

OpenCV wrapper for .NET
Apache License 2.0
5.42k stars 1.15k forks source link

Inrange method is invalid for cropped images #608

Closed Jakvic closed 5 years ago

Jakvic commented 5 years ago

Summary of your issue

Inrange method is useless for the image that use DrawImage method

Environment

win10+vs2017+opencvsharp4.0.0

Example code:

cut

paste your core code
`
using OpenCvSharp;
using OpenCvSharp.Extensions;
using static OpenCvSharp.Cv2;
using System.Drawing;
namespace RcoloR
{
    class Program
    {
        static Bitmap Mybmp = new Bitmap("E:/CVIMG/lenna.png");
        static void Main(string[] args)
        {
            using (new Window("SRC", WindowMode.Normal, Mybmp.ToMat())) ;   //source image

            Prtsc(Mybmp, out Bitmap dst);  //crop image           
            using (new Window("IMAGE_CUT", WindowMode.Normal, dst.ToMat())) ; //show the cropped image

            MyInrange(dst,out Bitmap dstbmp);   // Inrange 
            using (new Window("DST", WindowMode.Normal, dstbmp.ToMat()));  //show the inranged image

            WaitKey();
        }
        static void Prtsc(Bitmap src, out Bitmap dst)  // crop image
        {
            dst = new Bitmap(300,300);
            using (Graphics g = Graphics.FromImage(dst))
            {
                g.DrawImage(src,new Rectangle(0,0,300,300),new Rectangle(0,0,300,300),GraphicsUnit.Pixel);
            }
        }
        static void MyInrange(Bitmap bmpsrc,out Bitmap dstbmp) // Cv2.Inrange();
        {
            using (Mat src = BitmapConverter.ToMat(bmpsrc))
            using (Mat dst = new Mat())
            {
                Scalar low_value = new Scalar(100, 100, 100);
                Scalar high_value = new Scalar(255, 255, 255);
                InRange(src, low_value, high_value, dst);
                dstbmp = dst.ToBitmap();
            }
        }
    }
}
`

## Output:

paste your output

t3

shimat commented 5 years ago

The cause of this issue is Bitmap PixelFormat value that is not intended for you.

So, the Type() of dst.ToMat() is not 8UC3 but 8UC4, and the result of InRange is unintended.

Jakvic commented 5 years ago

Hi,Sorry to reply you so late,i find the solution

dst = new Bitmap(300,300,System.Drawing.Imaging.PixelFormat.Format24bppRgb);

Just change this row,it's ok; Thanks a lot ,love you so much;