当无法使用C#

时间:2019-05-12 14:52:04

标签: c# json api visual-studio-2013 alpr

我正在使用USB摄像头制作车牌识别系统。摄像机将扫描车牌号,并在标签上显示其详细信息。但是,如果摄像机没有扫描/检测到任何车牌,我希望系统显示警告错误,以表明摄像机没有识别出任何东西。我正在使用C#进行编码。如果摄像机未检测到任何牌照,您能帮助我如何显示警告的代码!

        private FilterInfoCollection CaptureDevices;
        private VideoCaptureDevice videoSource;
        private Int32 pictureCount = 0;
        private DateTime parkDate, parkTime;
        private static readonly HttpClient client = new HttpClient();

        List<Image> images;
        List<Result> results;

        private void Form1_Load(object sender, EventArgs e)
        {
            CaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            foreach (FilterInfo Device in CaptureDevices)
            {
                cboDevice.Items.Add(Device.Name);
            }
            cboDevice.SelectedIndex = 0;
            videoSource = new VideoCaptureDevice();

            timer1.Tick += new EventHandler(this.Timer1_Tick);
            timer1.Interval = (600) * (100);
            timer1.Enabled = true;
            timer1.Start();

            videoSource = new VideoCaptureDevice(CaptureDevices[cboDevice.SelectedIndex].MonikerString);
            videoSource.NewFrame += new NewFrameEventHandler(videoSource_NewFrame);
            videoSource.Start();

            cboParkNo.SelectedIndex = 0;
        }

        void videoSource_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
        {
            pbImage.Image = (Bitmap)eventArgs.Frame.Clone();
        }

        public static async Task<string> ProcessImage(string image_path)
        {
            string SECRET_KEY = "**";

            Byte[] bytes = File.ReadAllBytes(image_path);
            string imagebase64 = Convert.ToBase64String(bytes);

            var content = new StringContent(imagebase64);

            var response = await client.PostAsync("https://api.openalpr.com/v2/recognize_bytes?recognize_vehicle=1&country=my&secret_key=" + SECRET_KEY, content).ConfigureAwait(false);

            var buffer = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);

            var byteArray = buffer.ToArray();
            var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

            return responseString;
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            pbImage.Image.Save(pictureCount.ToString() + ".jpg", ImageFormat.Jpeg);
            Task<string> recognizeTask = Task.Run(() => ProcessImage(@"C:\Users\User\source\repos\CatcityLPR\bin\Debug\" + pictureCount.ToString() + ".jpg"));
            recognizeTask.Wait();
            string task_result = recognizeTask.Result;

            RootObject vehicresult = JsonConvert.DeserializeObject<RootObject>(task_result);

            if (vehicresult.results.Count == 0)
            {
                lblWarning.Text = "License plate cannot be recognized!";
                lblDate.Text = DateTime.Now.ToString("MMddyyyy");
                lblTime.Text = DateTime.Now.ToShortTimeString();
            }
            else
            {
                txtPlateNo.Text = vehicresult.results[0].plate.ToString();
                lblDate.Text = DateTime.Now.ToString("MMddyyyy");
                lblTime.Text = DateTime.Now.ToShortTimeString();

                parkDate = Convert.ToDateTime(lblDate.Text);
                parkTime = Convert.ToDateTime(lblTime.Text);

                SqlConnection conn = new SqlConnection(new DBConnection().ConnectionString);
                if (conn.State == System.Data.ConnectionState.Closed)
                    conn.Open();
                SqlDataReader dr;

                SqlCommand cmd = new SqlCommand("SELECT * FROM pmsVehicleRecord WHERE clVehicPlateNo='" + txtPlateNo.Text + "'", conn);

                dr = cmd.ExecuteReader();

                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        lblFullName.Text = dr["clFullName"].ToString();
                        lblUsername.Text = dr["clUsername"].ToString();
                        lblAddress.Text = dr["clAddress"].ToString();
                        lblPaymentMethod.Text = dr["clPaymentMethod"].ToString();
                    }

                    dr.Close();
                    SqlCommand cms = new SqlCommand("SELECT * FROM pmsParkingRecord WHERE parkVehicPlateNo ='" + txtPlateNo + "' AND parkDate='" + lblDate + "'", conn);
                    dr = cms.ExecuteReader();

                    if (dr.HasRows)
                    {
                        dr.Close();
                        SqlCommand cmt = new SqlCommand("UPDATE pmsParkingRecord SET parkExitTime='" + parkTime + "'");
                        cmt.Connection = conn;
                        if (conn.State == System.Data.ConnectionState.Closed)
                            conn.Open();
                        SqlDataReader ds = cmt.ExecuteReader();
                    }
                    else
                    {
                        dr.Close();
                        SqlCommand cmn = new SqlCommand("INSERT INTO pmsParkingRecord (parkUsername, parkFullName, parkAddress, parkVehicPlateNo, parkPaymentMethod, parkDate, parkEntryTime) VALUES ('" + lblUsername.Text + "', '" + lblFullName.Text + "', '" + lblAddress.Text + "', '" + txtPlateNo.Text + "', '" + lblPaymentMethod.Text + "', '" + parkDate + "', '" + parkTime + "')");
                        cmn.Connection = conn;
                        if (conn.State == System.Data.ConnectionState.Closed)
                            conn.Open();
                        SqlDataReader ds = cmn.ExecuteReader();
                    }
                }
                else
                {
                    lblWarning.Text = "License Plate No is not registered!";
                    btnEntry.Enabled = false;
                    btnExit.Enabled = false;
                }
                dr.Close();
            }

            pictureCount++;
       }

RootObject.cs

namespace CatcityLPR
{
    public class ProcessingTime
    {
        public double total { get; set; }
        public double plates { get; set; }
        public double vehicles { get; set; }
    }

    public class VehicleRegion
    {
        public int y { get; set; }
        public int x { get; set; }
        public int height { get; set; }
        public int width { get; set; }
    }

    public class Candidate
    {
        public int matches_template { get; set; }
        public string plate { get; set; }
        public double confidence { get; set; }
    }

    public class Coordinate
    {
        public int y { get; set; }
        public int x { get; set; }
    }

    public class Orientation
    {
        public double confidence { get; set; }
        public string name { get; set; }
    }

    public class Color
    {
        public double confidence { get; set; }
        public string name { get; set; }
    }

    public class Make
    {
        public double confidence { get; set; }
        public string name { get; set; }
    }

    public class BodyType
    {
        public double confidence { get; set; }
        public string name { get; set; }
    }

    public class Year
    {
        public double confidence { get; set; }
        public string name { get; set; }
    }

    public class MakeModel
    {
        public double confidence { get; set; }
        public string name { get; set; }
    }

    public class Vehicle
    {
        public List<Orientation> orientation { get; set; }
        public List<Color> color { get; set; }
        public List<Make> make { get; set; }
        public List<BodyType> body_type { get; set; }
        public List<Year> year { get; set; }
        public List<MakeModel> make_model { get; set; }
    }

    public class Result
    {
        public string plate { get; set; }
        public double confidence { get; set; }
        public int region_confidence { get; set; }
        public VehicleRegion vehicle_region { get; set; }
        public string region { get; set; }
        public int plate_index { get; set; }
        public double processing_time_ms { get; set; }
        public List<Candidate> candidates { get; set; }
        public List<Coordinate> coordinates { get; set; }
        public Vehicle vehicle { get; set; }
        public int matches_template { get; set; }
        public int requested_topn { get; set; }
    }

    public class RegionsOfInterest
    {
        public int y { get; set; }
        public int x { get; set; }
        public int height { get; set; }
        public int width { get; set; }
    }

    public class RootObject
    {
        public string uuid { get; set; }
        public string data_type { get; set; }
        public long epoch_time { get; set; }
        public ProcessingTime processing_time { get; set; }
        public int img_height { get; set; }
        public int img_width { get; set; }
        public List<Result> results { get; set; }
        public int credits_monthly_used { get; set; }
        public int version { get; set; }
        public int credits_monthly_total { get; set; }
        public bool error { get; set; }
        public List<RegionsOfInterest> regions_of_interest { get; set; }
        public int credit_cost { get; set; }
    }
}

预期输出应显示一条消息或警告,说明摄像机“无法识别任何车牌”。

1 个答案:

答案 0 :(得分:1)

您正在数组中寻找元素0,该元素不存在,这就是为什么会出现错误的原因。

if(vehicresult.results[0].plate.ToString() == "")

您可以通过

解决此问题
if(vehicresult.results.Count == 0)