AoiMethodRgb.cs 2.9 KB
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AOI
{
    /// <summary>
    /// 颜色抽取
    /// </summary>
    public class AoiMethodRgb : AoiMethod
    {
        public int minR = 1;
        public int maxR = 255;
        public int minG = 1;
        public int maxG = 255;
        public int minB = 1;
        public int maxB = 255;
        /// <summary>
        /// 抽取出的像素最小占比
        /// </summary>
        public float minRate = 0;
        /// <summary>
        /// 抽取出的像素最大占比
        /// </summary>
        public float maxRate = 100;

        public override ResultBean Check(Image standardImage, Image imageToCheck)
        {
            ResultBean resultBean = new ResultBean();
            bool needCut = true;
            Image standardRoiImg = GetRoiImage(standardImage, needCut);
            resultBean.standardRoiImage = standardRoiImg;

            Image currentRoiImg = GetRoiImage(imageToCheck, needCut);
            resultBean.currentRoiImage = currentRoiImg;
            float rate = GetRate(currentRoiImg, out Image dstImg);

            bool result = false;
            if(rate >= minRate && rate <= maxRate)
            {
                result = true;
            }
            resultBean.result = result;
            return resultBean;
        }

        public float GetRate(Image img, out Image dstImg)
        {
            float percent = 0;
            dstImg = null;
            bool needCut = true;
            Image currentRoiImg = GetRoiImage(img, needCut);
            if (currentRoiImg != null)
            {
                Mat originalRoiMat = ImageUtil.ToMat(currentRoiImg);
                Mat roiMat = new Mat();
                Cv2.CvtColor(originalRoiMat, roiMat, ColorConversionCodes.BGRA2BGR);

                Mat dst = new Mat();
                //如果不是矩形可能会把透明像素也计算进去,所以这里最小从1开始
                int lowR = minR > 0 ? minR : 1;
                int lowG = minG > 0 ? minG : 1;
                int lowB = minB > 0 ? minB : 1;
                Scalar minScalar = Scalar.FromRgb(lowR, lowG, lowB);
                Scalar maxScalar = Scalar.FromRgb(maxR, maxG, maxB);
                Cv2.InRange(roiMat, minScalar, maxScalar, dst);
                int count = Cv2.CountNonZero(dst);
                originalRoiMat.CopyTo(dst, dst);
                dstImg = ImageUtil.ToImage(dst);

                //计算总像素
                minScalar = Scalar.FromRgb(1, 1, 1);
                maxScalar = Scalar.FromRgb(255, 255, 255);
                Cv2.InRange(roiMat, minScalar, maxScalar, dst);
                int totalCount = Cv2.CountNonZero(dst);
                percent = count * 100.0f / totalCount;
            }
            return percent;
        }
    }
}