Marking.Template/Temp/Default.aspx.cs

1259 lines
48 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using Lucee.WebBase.Utils;
using Lucee.WebBase.Data;
using System.Drawing;
using Emgu.CV;
using Emgu.CV.Util;
using Emgu.CV.Structure;
using System.Drawing.Drawing2D;
using System.Net;
using Newtonsoft;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using MySql.Data.MySqlClient;
using Emgu.CV.Flann;
using System.Data.SqlTypes;
using System.Security.AccessControl;
using System.IO;
using System.Text.RegularExpressions;
public partial class _Default : System.Web.UI.Page
{
public long TempID = 0;
public long AnotherTempID = 0;
public string PageIndex = "0";
public string Bindlist = "";
public string imgage = "";
public string ExamNO = "";
public string isLocked = "";
public string HideAreaText = "";
public string IsPostionValue = "";
public long tenant = 0;
public string pager = "";
public int isHand = 0;
public string MainTempId = "0";
public int PageCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
int action = Globals.Request("action") == "" ? 0 : Convert.ToInt32(Globals.Request("action"));
tenant = Globals.Request("tenant") == "" ? 0 : Convert.ToInt64(Globals.Request("tenant"));
isHand = Globals.Request("isHand") == "" ? 0 : Convert.ToInt32(Globals.Request("isHand"));
pager = Globals.Request("pager").ToLower();
if (action != 0)
{
Response.Clear();
switch (action)
{
case 1:
UpdateTempData();
break;
// 锁定
case 2:
LockTemp();
break;
}
Response.End();
}
else
{
TempID = Globals.Request("TempID") == "" ? 0 : Convert.ToInt32(Globals.Request("TempID"));//获取小模板ID
if (TempID == 0)
{
Response.Write("<script>alert('无模板数据');window.close();</script>");
return;
}
string sql = "select * from MK_TempleteData where ID_bigint=" + TempID;
DataTable dtx = new MysqlDBHelper(tenant).ExecuteQuery(sql);
if (dtx.Rows.Count > 0)
{
Bindlist = dtx.Rows[0]["TempValue_nvarchar"].ToString();
imgage = dtx.Rows[0]["TempPicture64_nvarchar"].ToString();
isLocked = dtx.Rows[0]["islock_bit"] == null ? "" : dtx.Rows[0]["islock_bit"].ToString();
HideAreaText = dtx.Rows[0]["HideAreaPostionList_nvarchar"] == null ? "" : dtx.Rows[0]["HideAreaPostionList_nvarchar"].ToString();
IsPostionValue = dtx.Rows[0]["HideAreaPostionList_nvarchar"] == null ? "" : dtx.Rows[0]["HideAreaPostionList_nvarchar"].ToString();
PageIndex = dtx.Rows[0]["PageIndex_int"] == null ? "" : dtx.Rows[0]["PageIndex_int"].ToString();
MainTempId = dtx.Rows[0]["MainID_bigint"].ToString();
sql = "select MainPage_int,HasPosition from MK_TempleteMain where ID_bigint=" + MainTempId;
var maindt = new MysqlDBHelper(tenant).ExecuteQuery(sql);
if (maindt == null || maindt.Rows.Count <= 0)
{
Response.Write("<script>alert('主模板数据有问题');</script>");
return;
}
PageCount = Convert.ToInt32(maindt.Rows[0]["MainPage_int"]);
IsPostionValue = maindt.Rows[0]["HasPosition"].ToString();
if (PageCount > 1)
{
sql = "select ID_bigint from MK_TempleteData where MainID_bigint=" + MainTempId + " and ID_bigint!=" + TempID;
AnotherTempID = Convert.ToInt32(new MysqlDBHelper(tenant).ExecuteScalar(sql));
}
}
}
}
private void UpdateTempData()
{
TempID = Globals.Request("TempID") == "" ? 0 : Convert.ToInt32(Globals.Request("TempID"));//获取小模板ID
string totalHtml = Server.UrlDecode(Globals.Request("totalHtml"));
string HideAreaPostionList = Server.UrlDecode(Globals.Request("HideAreaPostionList"));
if (AnsyTemp(HideAreaPostionList, totalHtml))
{
string sql = "Update MK_TempleteData SET TempValue_nvarchar=@TempValue_nvarchar,HideAreaPostionList_nvarchar=@HideAreaPostionList_nvarchar where ID_bigint=" + TempID;
MySqlParameter[] sp = new MySqlParameter[] {
new MySqlParameter("@TempValue_nvarchar",totalHtml),
new MySqlParameter("@HideAreaPostionList_nvarchar",HideAreaPostionList)
};
string[] totalHtmlList = totalHtml.Split('$');
new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);
}
//if (new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp) == 1)
//{
// if (totalHtmlList[0] == "")
// {
// Response.Write("ok");
// }
// else
// {
// AnsyTemp(HideAreaPostionList);
// }
//}
//else {
// Response.Write("0");
//}
}
private void LockTemp()
{
TempID = Globals.Request("TempID") == "" ? 0 : Convert.ToInt32(Globals.Request("TempID"));//获取小模板ID
string totalHtml = Server.UrlDecode(Globals.Request("totalHtml"));
string HideAreaPostionList = Server.UrlDecode(Globals.Request("HideAreaPostionList"));
string[] totalHtmlList = totalHtml.Split('$');
if (AnsyTemp(HideAreaPostionList, totalHtml))
{
string sql = "Update MK_TempleteData SET TempValue_nvarchar=@TempValue_nvarchar,HideAreaPostionList_nvarchar=@HideAreaPostionList_nvarchar,islock_bit=1 where ID_bigint=" + TempID;
MySqlParameter[] sp = new MySqlParameter[] {
new MySqlParameter("@TempValue_nvarchar",totalHtml),
new MySqlParameter("@HideAreaPostionList_nvarchar",HideAreaPostionList)
};
AddQuestionData(totalHtml);
new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);
}
//if (new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp) == 1)
//{
// if (totalHtmlList[0] == "")
// {
// Response.Write("ok");
// }
// else {
// AnsyTemp(HideAreaPostionList);
// }
//}
//else
//{
// Response.Write("0");
//}
}
private void AddQuestionData(string totalHtml)
{
TempID = Convert.ToInt64(Globals.Request("TempID"));
string[] totalHtmlList = totalHtml.Split('$');
string kg = totalHtmlList[2];
string zg = totalHtmlList[3];
string[] questionlist = kg.Trim('^').Split('^');
string[] zglist = zg.Trim('^').Split('^');
string sql = "";
if (kg != "")
{
for (int i = 0; i < questionlist.Length; i++)
{
string[] detailtList = questionlist[i].Split(',');
string starNum = detailtList[4].ToUpper();
string endNum = detailtList[5].ToUpper();
string score = detailtList[9];
if (score == "")
{
score = "0";
}
string selectNum = detailtList[6];
string isselectmore = detailtList[8];
string bigNum = "";
if (starNum.Contains("M"))
{
bigNum = starNum.Split('M')[0];
int startSmallNum = Convert.ToInt32(starNum.Split('M')[1]);
int endSmallNum = Convert.ToInt32(endNum.Split('M')[1]);
for (int j = Convert.ToInt32(startSmallNum); j <= Convert.ToInt32(endSmallNum); j++)
{
sql = "SELECT COUNT(1) FROM MK_TempQuestionData WHERE TempID_bigint=" + TempID + " AND QuestionIndex_int='" + (bigNum + "." + j) + "'";
if (new MysqlDBHelper(tenant).ExecuteScalar(sql).ToString() == "0")
{
sql = "INSERT INTO MK_TempQuestionData(TempID_bigint,QuestionIndex_int,SmallQuestionDetail_nvarchar,Score_float,createdtime_datetime,smallQuestionNum_int,questiontype_int,selectNum_int,selecttype_int) VALUES(@TempID_bigint,@QuestionIndex_int,@SmallQuestionDetail_nvarchar,@Score_float,'" + DateTime.Now + "',@smallQuestionNum_int,0,@selectNum_int,@selecttype_int)";
MySqlParameter[] sp = new MySqlParameter[] {
new MySqlParameter("@TempID_bigint",TempID),
new MySqlParameter("@QuestionIndex_int",bigNum+"."+j),
new MySqlParameter("@SmallQuestionDetail_nvarchar",""),
new MySqlParameter("@smallQuestionNum_int","1"),
new MySqlParameter("@Score_float",score),
new MySqlParameter("@selectNum_int",selectNum),
new MySqlParameter("@selecttype_int",isselectmore),
};
new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);
}
}
}
else
{
for (int j = Convert.ToInt32(starNum); j <= Convert.ToInt32(endNum); j++)
{
sql = "SELECT COUNT(1) FROM MK_TempQuestionData WHERE TempID_bigint=" + TempID + " AND QuestionIndex_int='" + j + "'";
if (new MysqlDBHelper(tenant).ExecuteScalar(sql).ToString() == "0")
{
sql = "INSERT INTO MK_TempQuestionData(TempID_bigint,QuestionIndex_int,SmallQuestionDetail_nvarchar,Score_float,createdtime_datetime,smallQuestionNum_int,questiontype_int,selectNum_int,selecttype_int) VALUES(@TempID_bigint,@QuestionIndex_int,@SmallQuestionDetail_nvarchar,@Score_float,'" + DateTime.Now + "',@smallQuestionNum_int,0,@selectNum_int,@selecttype_int)";
MySqlParameter[] sp = new MySqlParameter[] {
new MySqlParameter("@TempID_bigint",TempID),
new MySqlParameter("@QuestionIndex_int",j),
new MySqlParameter("@SmallQuestionDetail_nvarchar",""),
new MySqlParameter("@smallQuestionNum_int","1"),
new MySqlParameter("@Score_float",score),
new MySqlParameter("@isSelectMore_bit",isselectmore),
new MySqlParameter("@selectNum_int",selectNum),
new MySqlParameter("@selecttype_int",isselectmore),
};
new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);
}
}
}
}
}
if (zg != "")
{
for (int i = 0; i < zglist.Length; i++)
{
string[] detailtList = zglist[i].Split(',');
bool issplit = false;
if (detailtList[4].Contains("X"))
{
issplit = true;
detailtList[4] = detailtList[4].Split('X')[0];
}
//sql = "SELECT COUNT(1) FROM MK_TempQuestionData WHERE TempID_bigint=" + TempID + " AND QuestionIndex_int='" + detailtList[4] + "'";
sql = String.Format("SELECT COUNT(1) FROM MK_TempQuestionData where TempID_bigint in(select ID_bigint from MK_TempleteData where MainID_bigint =(SELECT MainID_bigint FROM " +
"`MK_TempleteData` where ID_bigint={0})) AND QuestionIndex_int='{1}';", TempID, detailtList[4]);
string mkscoretype = "";
if (string.IsNullOrEmpty(detailtList[7]))
{
mkscoretype = "1";
}
else
{
mkscoretype = detailtList[7];
}
if (new MysqlDBHelper(tenant).ExecuteScalar(sql).ToString() == "0")
{
sql = "INSERT INTO MK_TempQuestionData(TempID_bigint,QuestionIndex_int,SmallQuestionDetail_nvarchar,Score_float,createdtime_datetime,smallQuestionNum_int,questiontype_int,mkscoretype_float,is_split) VALUES(@TempID_bigint,@QuestionIndex_int,@SmallQuestionDetail_nvarchar,@Score_float,'" + DateTime.Now + "',@smallQuestionNum_int,1,@mkscoretype_float,@is_split)";
MySqlParameter[] sp = new MySqlParameter[] {
new MySqlParameter("@TempID_bigint",TempID),
new MySqlParameter("@QuestionIndex_int",detailtList[4]),
new MySqlParameter("@SmallQuestionDetail_nvarchar",""),
new MySqlParameter("@Score_float",detailtList[6]==""? "0" : detailtList[6]),
new MySqlParameter("@smallQuestionNum_int",detailtList[5]),
new MySqlParameter("@mkscoretype_float",mkscoretype),
new MySqlParameter("@is_split",issplit)
};
new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp);
}
}
}
}
/// <summary>
/// 锁定模板数据
/// </summary>
public bool AnsyTemp(string HideAreaPostionList, string totalHtml)
{
try
{
CommonUse commonUse = new CommonUse();
long TempID = Convert.ToInt64(Globals.Request("TempID"));
string sql = "SELECT * FROM MK_TempleteData WHERE ID_bigint=" + TempID;
DataTable dt = new MysqlDBHelper(tenant).ExecuteQuery(sql);
if (dt.Rows.Count <= 0)
{
Response.Write("NO DATA");
return false;
}
Bitmap PictureBoxBitMap = UrlToImage(dt.Rows[0]["TempPicture64_nvarchar"].ToString());
if (PictureBoxBitMap == null)
{
Response.Write("NO PICTURE");
}
string[] GetData = totalHtml.Split('$');
string PYPostionList = "0,0";
if (GetData[0] != "")//如果有定位点
{
//计算模板图片参数
double xielv = 0;
int width = Convert.ToInt32(GetData[6].Split(',')[0]);
int height = Convert.ToInt32(GetData[6].Split(',')[1]);
PictureBoxBitMap = ScaleToSize(PictureBoxBitMap, width, height);
Image<Gray, byte> currentFramext = new Image<Gray, byte>(PictureBoxBitMap);
Image<Gray, byte> myImage = new Image<Gray, byte>(commonUse.FilterRed(PictureBoxBitMap));
// 进行中值滤波
CvInvoke.MedianBlur(myImage, myImage, 5);
// 进行高斯滤波
CvInvoke.GaussianBlur(myImage, myImage, new Size(5, 5), 0);
// 去除定位点周围噪点
//Image<Bgr, byte> blur = myImage.AddWeighted(myImage, 1.9, -0.5, 0);
Bitmap bm_dest = myImage.Bitmap;
Image<Gray, byte> EmguImagex1 = new Image<Gray, byte>(bm_dest);
Mat mat_threshold1 = new Mat();
CvInvoke.Threshold(EmguImagex1, mat_threshold1, 210, 255, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
Mat mat_dilate = commonUse.MyDilate(mat_threshold1);
VectorOfVectorOfPoint selected_contours1 = commonUse.GetUsefulContoursDingWei(mat_dilate, 1);
//var color_mat1 = commonUse.DrawContours(mat_dilate, selected_contours1);
//commonUse.ShowMatWaitKey("44444", color_mat1, 0.8);
////Response.Write(ImgToBase64String(color_mat1.Bitmap));
//return false;
//Image<Gray, byte> imagex = new Image<Gray, byte>(PictureBoxBitMap);
//Mat mat_threshold1 = new Mat();
//CvInvoke.Threshold(imagex, mat_threshold1, 160, 255, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
//Mat mat_dilate1 = commonUse.MyDilate(mat_threshold1);
//VectorOfVectorOfPoint selected_contours1;
//selected_contours1 = commonUse.GetUsefulContoursDingWei(mat_dilate1, 1);
string message = string.Empty;
Mat color_mxxx = commonUse.GetPostionXYByFindPostionAndXieLv(currentFramext.Mat, selected_contours1, GetData[0], out PYPostionList, currentFramext, out xielv, out message);
if (xielv == -100)
{
Response.Write(message);
return false;
}
int oldWidth = color_mxxx.Bitmap.Width;
int oldHeight = color_mxxx.Bitmap.Height;
string tempEx = TempV(GetData, PYPostionList, oldWidth, oldHeight, HideAreaPostionList);
if (tempEx != "ok")
{
Response.Write(tempEx);
return false;
}
int PageIndex = Convert.ToInt32(Globals.Request("PageIndex"));
if (PageIndex == 1)
{
//计算标准点
int mx = GetOtherBitmaplist(currentFramext.Mat, 160, PYPostionList.Split(','), GetData[9]);
if (mx == 0)
{
Response.Write("标准点数据错误,请重新框选");
return false;
}
else
{
long MainTempId = Convert.ToInt64(Globals.Request("MainTempId"));
sql = "UPDATE MK_TempleteMain SET option_pixel_options=" + mx + " WHERE ID_bigint=" + MainTempId;
new MysqlDBHelper(tenant).ExecuteNoQuery(sql);
}
// 存在锚定点数据则判断锚定点内容
//if (!string.IsNullOrWhiteSpace(GetData[10]) && GetData[10].Split(',').Length == 6)
//{
// //计算锚定点
// var ocrResultText = string.Empty;
// if (!GetMaoDingDian(PictureBoxBitMap, GetData[10], out ocrResultText))
// {
// Response.Write("未找到匹配的文字,识别结果【" + ocrResultText+"】");
// return false;
// }
//}
}
sql = "UPDATE MK_TempleteData SET XieLv_float =@XieLv_float,CutWidth_int=@CutWidth_int,CutHeight_int=@CutHeight_int,PyPPostion_nvarchar=@PyPPostion_nvarchar WHERE ID_bigint=" + TempID;
MySqlParameter[] sp = new MySqlParameter[] {
new MySqlParameter("@XieLv_float",xielv),
new MySqlParameter("@CutWidth_int",oldWidth),
new MySqlParameter("@CutHeight_int",oldHeight),
new MySqlParameter("@PyPPostion_nvarchar",PYPostionList)
};
if (new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp) > 0)
{
}
currentFramext.Dispose();
color_mxxx.Dispose();
PictureBoxBitMap.Dispose();
Response.Write("ok");
return true;
}
else
{
int width = Convert.ToInt32(GetData[6].Split(',')[0]);
int height = Convert.ToInt32(GetData[6].Split(',')[1]);
PictureBoxBitMap = ScaleToSize(PictureBoxBitMap, width, height);
Image<Gray, byte> imagex = new Image<Gray, byte>(PictureBoxBitMap);
Mat mat_threshold1 = new Mat();
CvInvoke.Threshold(imagex, mat_threshold1, 160, 255, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
Mat mat_dilate1 = commonUse.MyDilate(mat_threshold1);
VectorOfVectorOfPoint selected_contours1;
selected_contours1 = commonUse.GetUsefulContoursDingWei(mat_dilate1, 1);
Image<Gray, byte> currentFramext = new Image<Gray, byte>(PictureBoxBitMap);
int PageIndex = Convert.ToInt32(Globals.Request("PageIndex"));
if (PageIndex == 1)
{
int mx = GetOtherBitmaplist(currentFramext.Mat, 160, PYPostionList.Split(','), GetData[9]);
long MainTempId = Convert.ToInt64(Globals.Request("MainTempId"));
if (mx == 0)
{
Response.Write("标准点数据错误,请重新框选");
return false;
}
else
{
sql = "UPDATE MK_TempleteMain SET option_pixel_options=" + mx + " WHERE ID_bigint=" + MainTempId;
new MysqlDBHelper(tenant).ExecuteNoQuery(sql);
}
}
//计算模板图片参数
double xielv = 0;
width = Convert.ToInt32(GetData[6].Split(',')[0]);
height = Convert.ToInt32(GetData[6].Split(',')[1]);
sql = "UPDATE MK_TempleteData SET XieLv_float =@XieLv_float,CutWidth_int=@CutWidth_int,CutHeight_int=@CutHeight_int,PyPPostion_nvarchar=@PyPPostion_nvarchar WHERE ID_bigint=" + TempID;
MySqlParameter[] sp = new MySqlParameter[] {
new MySqlParameter("@XieLv_float",xielv),
new MySqlParameter("@CutWidth_int",width),
new MySqlParameter("@CutHeight_int",height),
new MySqlParameter("@PyPPostion_nvarchar",PYPostionList)
};
if (new MysqlDBHelper(tenant).ExecuteNoQuery(sql, sp) > 0)
{
}
PictureBoxBitMap.Dispose();
Response.Write("ok");
return true;
}
}
catch (Exception ex)
{
return false;
Response.Write("TEMPERRO");
}
}
/// <summary>
/// 获取其他截图
/// </summary>
/// <param name="color_mat"></param>
/// <param name="PYPostion"></param>
/// <param name="postiontiaomaX"></param>
/// <param name="selected_contours"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
public static int GetOtherBitmaplist(Mat color_mat, int Threshold, string[] PYPostion, string postiontiaomaX)
{
CommonUse commonUse = new CommonUse();
string[] quekao = postiontiaomaX.Split(',');
//int X = Convert.ToInt32(Convert.ToDouble(quekao[0])) - Convert.ToInt32(PYPostion[0]);
//int Y = Convert.ToInt32(Convert.ToDouble(quekao[1])) - Convert.ToInt32(PYPostion[1]);
int X = Convert.ToInt32(Convert.ToDouble(quekao[0]));
int Y = Convert.ToInt32(Convert.ToDouble(quekao[1]));
int W = Convert.ToInt32(Convert.ToDouble(quekao[2]));
int H = Convert.ToInt32(Convert.ToDouble(quekao[3]));
int xuanXiang = 1;//选项数量
int tiliang = 1;//题量
//string mx = "";
int wL = Convert.ToInt32(W / xuanXiang);
int hL = Convert.ToInt32(H / tiliang);
Image<Gray, byte> bytimg = GetMatCutImg(color_mat.Bitmap, X, Y, W, H);
//Bitmap bmp = ScaleToSize(tempImage.Bitmap, tempImage.Bitmap.Width * 4, tempImage.Bitmap.Height * 4, groupNo);
X = 0; Y = 0;
Mat src = bytimg.Mat;
Mat mat_threshold = new Mat();
CvInvoke.Threshold(src, mat_threshold, Threshold, 254, Emgu.CV.CvEnum.ThresholdType.BinaryInv);
Mat mat_dilate = commonUse.MyDilate(mat_threshold);
VectorOfVectorOfPoint selected_contours;
int option_pixel_options = 0;
selected_contours = GetUsefulContoursSelectoOptionQK(mat_dilate, 1, out option_pixel_options);
//mx = GetValueAndDrawGrid_Other(src.Bitmap, selected_contours, X, wL, xuanXiang, Y, hL, tiliang, "");
bytimg.Dispose();
src.Dispose();
return option_pixel_options;
}
/// <summary>
/// 获取其他截图
/// </summary>
/// <param name="color_mat"></param>
/// <param name="PYPostion"></param>
/// <param name="postiontiaomaX"></param>
/// <param name="selected_contours"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
public static bool GetMaoDingDian(Bitmap srcBimap, string positionStr, out string ocrResultText)
{
ocrResultText = string.Empty;
CommonUse commonUse = new CommonUse();
string[] ocrText = positionStr.Split(',');
int X = Convert.ToInt32(Convert.ToDouble(ocrText[0]));
int Y = Convert.ToInt32(Convert.ToDouble(ocrText[1]));
int W = Convert.ToInt32(Convert.ToDouble(ocrText[2]));
int H = Convert.ToInt32(Convert.ToDouble(ocrText[3]));
Image<Gray, byte> bytimg = GetMatCutImg(srcBimap, X, Y, W, H);
//commonUse.ShowMatWaitKey("maodingdian", bytimg.Mat, 2);
////var ocrResult = OcrHelper.GetOcrResult(bytimg.Bitmap);
////if (ocrResult == null || string.IsNullOrWhiteSpace(ocrResult.Text))
////{
//// // 未找到任何文字
//// return false;
////}
//ocrResultText = ocrResult.Text;
//if (bytimg != null)
//{
// bytimg.Dispose();
//}
//var ocrResultArr = ocrResult.Text.ToCharArray();
//var ocrTestArr = ocrText[5].ToCharArray();
//var interList = ocrTestArr.Intersect(ocrResultArr);
//if (interList.Count() == ocrTestArr.Length)
//{
// // 找到输入文字
// return true;
//}
//ocrResultText = ocrResult.Text;
// 未找到输入文字
return false;
}
/// <summary>
/// 筛选图中符合给定条件的轮廓
/// </summary>
/// <param name="mat_threshold">要提取轮廓的图片</param>
/// <param name="width1">轮廓外接矩形大于该宽度值</param>
/// <param name="width2">轮廓外接矩形小于该宽度值</param>
/// <param name="height1">轮廓外接矩形大于该高度值</param>
/// <param name="height2">轮廓外接矩形小于该高度值</param>
public static VectorOfVectorOfPoint GetUsefulContoursSelectoOptionQK(Mat mat, double ratio, out int option_pixel_options)
{
option_pixel_options = 0;
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();//所有的轮廓
VectorOfVectorOfPoint selected_contours = new VectorOfVectorOfPoint();//用于存储筛选过后的轮廓
CvInvoke.FindContours(mat, contours, null, Emgu.CV.CvEnum.RetrType.External,
Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);//提取所有轮廓,操作过程中会对输入图像进行修改
//筛选轮廓。筛选条件:长宽比大于给定值
for (int i = 0; i < contours.Size; i++)
{
Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);//外接矩形
Mat temp = new Mat(mat, rect);//提取ROI矩形区域
int pxNums = CvInvoke.CountNonZero(temp);//计算图像内非零像素个数
double area = CvInvoke.ContourArea(contours[i]);//计算连通轮廓的面积
double length = CvInvoke.ArcLength(contours[i], false); //计算连通轮廓的周长
VectorOfPoint approx_curve = new VectorOfPoint();//用于存放逼近的结果
CvInvoke.ApproxPolyDP(contours[i], approx_curve, length * 0.02, true);
//bool bo = (area > 500 && area < 12000);//&& rect.Height<100
//bool bo = ((area > 20 && area < 150000) && rect.Height > 8 );
bool bo = ((area > 10 && area < 150000) && rect.Height > 5);
if (bo)
{
if (pxNums > (area * 0.7))
{
option_pixel_options = pxNums;
selected_contours.Push(contours[i]);
}
}
}
return selected_contours;
}
public static VectorOfVectorOfPoint GetUsefulContoursForMaoDingDian(Mat mat)
{
VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();//所有的轮廓
VectorOfVectorOfPoint selected_contours = new VectorOfVectorOfPoint();//用于存储筛选过后的轮廓
CvInvoke.FindContours(mat, contours, null, Emgu.CV.CvEnum.RetrType.List,
Emgu.CV.CvEnum.ChainApproxMethod.ChainApproxSimple);//提取所有轮廓,操作过程中会对输入图像进行修改
//筛选轮廓。筛选条件:长宽比大于给定值
for (int i = 0; i < contours.Size; i++)
{
Rectangle rect = CvInvoke.BoundingRectangle(contours[i]);//外接矩形
Mat temp = new Mat(mat, rect);//提取ROI矩形区域
int pxNums = CvInvoke.CountNonZero(temp);//计算图像内非零像素个数
double area = CvInvoke.ContourArea(contours[i]);//计算连通轮廓的面积
double length = CvInvoke.ArcLength(contours[i], false); //计算连通轮廓的周长
VectorOfPoint approx_curve = new VectorOfPoint();//用于存放逼近的结果
CvInvoke.ApproxPolyDP(contours[i], approx_curve, length * 0.02, true);
bool bo = ((area > 10 && area < 150000) && rect.Height > 5 && rect.Width > 5);
if (bo)
{
selected_contours.Push(contours[i]);
}
}
return selected_contours;
}
/// <summary>
/// 画出网格并返回填图结果
/// </summary>
/// <param name="img"></param>
/// <param name="contours"></param>
/// <param name="x_begin">左边距</param>
/// <param name="x_interval">方块长度</param>
/// <param name="x_num">方块数量</param>
/// <param name="y_begin">上边距</param>
/// <param name="y_interval">方块高度</param>
/// <param name="y_num">方块竖数量</param>
/// <param name="strText">输出文字</param>
/// <returns></returns>
public static string GetValueAndDrawGrid_Other(Bitmap img, VectorOfVectorOfPoint contours,
int x_begin, int x_interval, int x_num, int y_begin, int y_interval, int y_num, string strText)
{
//画网格
//Mat mat_grid = DrawGridByXY(img, x_begin, x_interval, x_num, y_begin, y_interval, y_num);
int[] intArray = GetTargetValues_L_Other(contours, x_begin, x_interval, x_num, y_begin, y_interval, y_num, img, strText);
int maxValue = GetMaxValueOfArray(intArray);//数组最大值
string str = "";
//str += Environment.NewLine;//回车
str += strText;
if (maxValue >= 4 && maxValue < 10)
{
str += GetStringOfIntArray(intArray, "ABCDEFGH");
}
else
{
if (maxValue >= 10)
{
str += GetStringOfIntArray(intArray, "ABCDEFGH");
}
else
{
str += GetStringOfIntArray(intArray, "ABCDEFGH");
}
}
return str;
}
/// <summary>
/// 拼接给定int数组内容并返回拼接后字符串
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
public static string GetStringOfIntArray(int[] arr, string ss = "ABCD")
{
string str = "";
//char[] ch = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
char[] ch = ss.ToCharArray();
foreach (int a in arr)
{
///
if (a >= 10)
{
string x = a.ToString();
char[] cc = x.ToArray();
int[] result = new int[cc.Length];
for (int i = 0; i < cc.Length; i++)
{
result[i] = Convert.ToInt32(x.Substring(i, 1));
}
Array.Sort(result);
int[] finalResult = result;
for (int j = 0; j < finalResult.Length; j++)
{
if (finalResult[j] == -1)
{
str += "null";
}
else
{
str += ch[finalResult[j]];
}
}
str += " ";
}
else
{
if (a == -1)
{
str += "null ";//未识别时,标示为空
}
else
{
str += ch[a] + " ";
}
}
}
return str;
}
/// <summary>
/// 获取一维int数组中最大值
/// </summary>
/// <param name="arr"></param>
/// <returns></returns>
public static int GetMaxValueOfArray(int[] arr)
{
int[] dst = new int[arr.Length];
Array.Copy(arr, dst, arr.Length);//深度复制数组,防止排序对原数组产生影响
Array.Sort(dst);//数组排序
int maxValue = dst[arr.Length - 1];//数组最大值
return maxValue;
}
// <summary>
/// 根据给定的轮廓及范围信息计算涂卡的结果返回int数组
/// </summary>
/// <param name="contours"></param>
/// <param name="x"></param>
/// <param name="x_interval"></param>
/// <param name="x_num"></param>
/// <param name="y"></param>
/// <param name="y_interval"></param>
/// <param name="y_num"></param>
/// <returns></returns>
public static int[] GetTargetValues_L_Other(VectorOfVectorOfPoint contours, int x_begin, int x_interval, int x_num,
int y_begin, int y_interval, int y_num, Bitmap img, string strText)
{
int[] result = new int[y_num];//结果数组
//数组初值默认为-1
for (int i = 0; i < y_num; i++)
{
result[i] = -1;
}
int x_max = x_begin + x_interval * x_num;
int y_max = y_begin + y_interval * y_num;
VectorOfVectorOfPoint targetContours = new VectorOfVectorOfPoint();
Point[] gravity = GetGravityOfContours(contours);//轮廓中心点坐标
for (int i = 0; i < contours.Size; i++)
{
VectorOfPoint contour = contours[i];
if (gravity[i].X < x_begin || gravity[i].X > x_max || gravity[i].Y < y_begin || gravity[i].Y > y_max)
{
continue;//判断中心点是否超出范围
}
int x_id = (int)Math.Floor((double)(gravity[i].Y - y_begin) / y_interval);//向右取整数
int value = (int)Math.Floor((double)(gravity[i].X - x_begin) / x_interval);
if (result[x_id] != -1)
{
}
else
{
result[x_id] = value;
}
}
return result;
}
/// <summary>
/// 计算轮廓中心点坐标
/// </summary>
/// <param name="selected_contours">要计算中心点的轮廓</param>
/// <returns></returns>
public static Point[] GetGravityOfContours(VectorOfVectorOfPoint selected_contours)
{
int ksize = selected_contours.Size;
double[] m00 = new double[ksize];
double[] m01 = new double[ksize];
double[] m10 = new double[ksize];
Point[] gravity = new Point[ksize];//用于存储轮廓中心点坐标
MCvMoments[] moments = new MCvMoments[ksize];
for (int i = 0; i < ksize; i++)
{
VectorOfPoint contour = selected_contours[i];
//计算当前轮廓的矩
moments[i] = CvInvoke.Moments(contour, false);
m00[i] = moments[i].M00;
m01[i] = moments[i].M01;
m10[i] = moments[i].M10;
int x = Convert.ToInt32(m10[i] / m00[i]);//计算当前轮廓中心点坐标
int y = Convert.ToInt32(m01[i] / m00[i]);
gravity[i] = new Point(x, y);
}
return gravity;
}
/// <summary>
/// 获取裁剪 L T W H
/// </summary>
/// <param name="PointPath"></param>
public static Image<Gray, byte> GetMatCutImg(Bitmap bmp, int sX, int sT, int sW, int sH)
{
List<Image<Gray, byte>> postionimageCut = new List<Image<Gray, byte>>();
int L = sX;
int T = sT;
int W = sW;
int H = sH;
Rectangle rectangle = new Rectangle(L, T, W, H);
Image<Gray, byte> Sub = new Image<Gray, byte>(bmp).GetSubRect(rectangle);
Image<Gray, byte> CropImage = new Image<Gray, byte>(Sub.Size);
CvInvoke.cvCopy(Sub, CropImage, IntPtr.Zero);
return CropImage;
}
/// <summary>
/// 检查边距是否合格
/// </summary>
/// <param name="getdata"></param>
private string TempV(string[] GetData, string PYPostionList, int oldWidth, int oldHeight, string HideAreaPostionList)
{
double pyLeft = Convert.ToInt32(PYPostionList.Split(',')[0]);
double pyTop = Convert.ToInt32(PYPostionList.Split(',')[1]);
double Xtop = 0;
double Xleft = 0;
double Xwidth = 0;
double Xheight = 0;
if (GetData[1] != "")
{
string[] list = GetData[1].Split(',');
Xleft = Convert.ToDouble(list[0]);
Xtop = Convert.ToDouble(list[1]);
Xwidth = Convert.ToDouble(list[2]);
Xheight = Convert.ToDouble(list[3]);
if (Xleft < pyLeft)
{
return "学号编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "学号编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "学号编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "学号编辑框下边超过定位点边界!";
}
}
if (GetData[2] != "")//客观题
{
string[] keguantiList = GetData[2].Split('^');
foreach (string slist in keguantiList)
{
string[] list = slist.Split(',');
Xleft = Convert.ToDouble(list[0]);
Xtop = Convert.ToDouble(list[1]);
Xwidth = Convert.ToDouble(list[2]);
Xheight = Convert.ToDouble(list[3]);
string tihao = list[4] + "-" + list[5];
if (Xleft < pyLeft)
{
return "客观题:[" + tihao + "] 编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "客观题:[" + tihao + "]编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "客观题:[" + tihao + "] 编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "客观题:[" + tihao + "] 编辑框下边超过定位点边界!";
}
}
}
if (GetData[3] != "")//主观题
{
string[] keguantiList = GetData[3].Split('^');
foreach (string slist in keguantiList)
{
string[] list = slist.Split(',');
Xleft = Convert.ToDouble(list[0]);
Xtop = Convert.ToDouble(list[1]);
Xwidth = Convert.ToDouble(list[2]);
Xheight = Convert.ToDouble(list[3]);
string tihao = list[4];
if (Xleft < pyLeft)
{
return "主观题:[" + tihao + "] 编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "主观题:[" + tihao + "] 编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "主观题:[" + tihao + "] 编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "主观题:[" + tihao + "] 编辑框下边超过定位点边界!";
}
}
}
if (GetData[4] != "")//主观题
{
string[] keguantiList = GetData[4].Split('^');
foreach (string slist in keguantiList)
{
string[] list = slist.Split(',');
Xleft = Convert.ToDouble(list[0]);
Xtop = Convert.ToDouble(list[1]);
Xwidth = Convert.ToDouble(list[2]);
Xheight = Convert.ToDouble(list[3]);
string tihao = list[4];
if (Xleft < pyLeft)
{
return "题号:[" + tihao + "] 编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "题号:[" + tihao + "] 编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "题号:[" + tihao + "] 编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "题号:[" + tihao + "] 编辑框下边超过定位点边界!";
}
}
}
if (GetData[5] != "")
{
string[] list = GetData[5].Split(',');
Xleft = Convert.ToDouble(list[0]);
Xtop = Convert.ToDouble(list[1]);
Xwidth = Convert.ToDouble(list[2]);
Xheight = Convert.ToDouble(list[3]);
if (Xleft < pyLeft)
{
return "条码编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "条码编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "条码编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "条码编辑框下边超过定位点边界!";
}
}
if (GetData[7] != "")
{
string[] list = GetData[7].Split(',');
Xleft = Convert.ToDouble(list[0]);
Xtop = Convert.ToDouble(list[1]);
Xwidth = Convert.ToDouble(list[2]);
Xheight = Convert.ToDouble(list[3]);
if (Xleft < pyLeft)
{
return "条码编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "条码编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "条码编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "条码编辑框下边超过定位点边界!";
}
}
if (GetData[8] != "")
{
string[] datipiyue = GetData[8].Split('^');
foreach (string slist in datipiyue)
{
string[] list = slist.Split(',');
Xleft = Convert.ToDouble(list[0]);
Xtop = Convert.ToDouble(list[1]);
Xwidth = Convert.ToDouble(list[2]);
Xheight = Convert.ToDouble(list[3]);
string tihao = list[4];
if (Xleft < pyLeft)
{
return "题号:[" + tihao + "]批阅分数编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "题号:[" + tihao + "]批阅分数编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "题号:[" + tihao + "]批阅分数编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "题号:[" + tihao + "]批阅分数编辑框下边超过定位点边界!";
}
}
}
if (HideAreaPostionList != "")
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
List<HideAreaData> ht = javaScriptSerializer.Deserialize<List<HideAreaData>>(HideAreaPostionList);
int count = 0;
foreach (HideAreaData h in ht)
{
count++;
Xleft = Convert.ToDouble(h.left);
Xtop = Convert.ToDouble(h.top);
Xwidth = Convert.ToDouble(h.width);
Xheight = Convert.ToDouble(h.height);
if (Xleft < pyLeft)
{
return "屏蔽区" + count + "编辑框左边超过定位点边界!";
}
if (Xleft + Xwidth - pyLeft > oldWidth)
{
return "屏蔽区" + count + "编辑框右边超过定位点边界!";
}
if (Xtop < pyTop)
{
return "屏蔽区" + count + "编辑框上边超过定位点边界!";
}
if (Xtop + Xheight - pyTop > oldHeight)
{
return "屏蔽区" + count + "编辑框下边超过定位点边界!";
}
}
}
return "ok";
}
private Bitmap ScaleToSize(Bitmap bitmap, int width, int height)
{
if (bitmap == null)
{
return null;
}
if (bitmap.Width == width && bitmap.Height == height)
{
return bitmap;
}
var scaledBitmap = new Bitmap(width, height);
using (var g = Graphics.FromImage(scaledBitmap))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(bitmap, 0, 0, width, height);
}
return scaledBitmap;
}
// <summary>
/// 图片另存为
/// </summary>
/// <param name="url">路径</param>
public Bitmap ImgGet(string url)
{
WebRequest imgRequest = WebRequest.Create(url);
HttpWebResponse res;
try
{
res = (HttpWebResponse)imgRequest.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
if (res.StatusCode.ToString() == "OK")
{
return new Bitmap((System.Drawing.Image)new Bitmap(imgRequest.GetResponse().GetResponseStream()));
}
else
{
return null;
}
}
public static string ImgToBase64String(Bitmap bmp)
{
try
{
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Dispose();
ms.Close();
return Convert.ToBase64String(arr);
}
catch (Exception ex)
{
return null;
}
}
public static Bitmap UrlToImage(string url)
{
WebRequest imgRequest = WebRequest.Create(url);
HttpWebResponse res = null;
try
{
res = (HttpWebResponse)imgRequest.GetResponse();
imgRequest.Timeout = 50000;
if (res.StatusCode.ToString() == "OK")
{
var tempbitmap = new Bitmap(imgRequest.GetResponse().GetResponseStream());
// 别删!图片和网页中的方向不一致,根据图片中的方向信息,旋转图片后识别
return new CommonUse().RotateByOrientation(tempbitmap);
}
else
{
return null;
}
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
return null;
}
finally
{
if (res != null)
{
res.Dispose();
res.Close();
}
imgRequest.Abort();
}
}
}
public class HideAreaData
{
public Double width { get; set; }
public Double height { get; set; }
public Double left { get; set; }
public Double top { get; set; }
}