| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759 | #pragma once#include "stdafx.h" #include <opencv2/core/core.hpp>  #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp>#include "OTSImageProcess.h"#include "OTSImageProcessParam.h"#include <OTSFieldData.h>#include "../OTSLog/COTSUtilityDllFunExport.h"#include "FieldMgr.h"using namespace cv;using namespace std;namespace OTSIMGPROC{   	namespace 	{				/***** 求两点间距离*****/		float getDistance(Point pointO, Point pointA)		{			float distance;			distance = powf((pointO.x - pointA.x), 2) + powf((pointO.y - pointA.y), 2);			distance = sqrtf(distance);			return distance;		}		/***** 点到直线的距离:P到AB的距离*****/		//P为线外一点,AB为线段两个端点		float  getDist_P2L(Point pointP, Point pointA, Point pointB)		{			//求直线方程			int A = 0, B = 0, C = 0;			A = pointA.y - pointB.y;			B = pointB.x - pointA.x;			C = pointA.x*pointB.y - pointA.y*pointB.x;			//代入点到直线距离公式			float distance = 0;			distance = ((float)abs(A*pointP.x + B * pointP.y + C)) / ((float)sqrtf(A*A + B * B));			return distance;		}		int  Side(Point P1, Point P2, Point point)		{			/*Point P1 = line.P1;			Point P2 = line.P2;*/			return ((P2.y - P1.y) * point.x + (P1.x - P2.x) * point.y + (P2.x*P1.y - P1.x*P2.y));		}		void  FindInnerCircleInContour(vector<Point> contour, Point ¢er, int &radius)		{			Rect r = boundingRect(contour);			int nL = r.x, nR = r.br().x; //轮廓左右边界			int nT = r.y, nB = r.br().y; //轮廓上下边界			double dist = 0;			double maxdist = 0;			for (int i = nL; i < nR; i++)  //列			{				for (int j = nT; j < nB; j++)  //行				{					//计算轮廓内部各点到最近轮廓点的距离					dist = pointPolygonTest(contour, Point(i, j), true);					if (dist > maxdist)					{						//求最大距离,只有轮廓最中心的点才距离最大						maxdist = dist;						center = Point(i, j);					}				}			}			radius = maxdist;  //圆半径		}		BOOL GetParticleAverageChord(std::vector<Point>  listEdge, double a_PixelSize, double &dPartFTD)		{			// safety check			double nx = 0, ny = 0;			Moments mu;			mu = moments(listEdge, false);			nx = mu.m10 / mu.m00;			ny = mu.m01 / mu.m00;			//circle(cvcopyImg, Point(nx, ny), 1, (255), 1);			Point ptCenter = Point((int)nx, (int)ny);			// coordinate transformation			Point ptPosition;			int radiusNum = 0;			// get ferret diameter			double sumFltDiameter = 0;			int interval;			int edgePointNum = listEdge.size();			if (edgePointNum > 10)			{				interval = edgePointNum / 10;//get one line per 10 degree  aproxemately 			}			else			{				interval = 1;			}			for (int i = 0; i < edgePointNum; i++)			{				Point pt = listEdge[i];				ptPosition.x = abs(pt.x - ptCenter.x);				ptPosition.y = abs(pt.y - ptCenter.y);				if (i % interval == 0)//calculate one line per 10 point ,so to speed up.don't calculate all the diameter.				{					double r1 = sqrt(pow(ptPosition.x, 2) + pow(ptPosition.y, 2));					sumFltDiameter += r1;					radiusNum += 1;					//line(cvImageData, ptCenter, pt, Scalar(nBlackColor), nThickness, nLineType);				}			}			if (radiusNum == 0)			{				dPartFTD = 0;			}			else			{				dPartFTD = a_PixelSize * sumFltDiameter / radiusNum * 2;			}			//imshow("feret center", cvImageData);			return TRUE;		}		void linearSmooth5(WORD wordIn[], WORD wordOut[], int N = 255)//smooth algorithm		{			double in[256];			double out[256];			double smoothCurveData[256];			for (int i = 0; i < 256; i++)			{				in[i] = (double)wordIn[i];			}			int i;			if (N < 5)			{				for (i = 0; i <= N - 1; i++)				{					out[i] = in[i];				}			}			else			{				out[0] = (3.0 * in[0] + 2.0 * in[1] + in[2] - in[4]) / 5.0;				out[1] = (4.0 * in[0] + 3.0 * in[1] + 2 * in[2] + in[3]) / 10.0;				for (i = 2; i <= N - 3; i++)				{					out[i] = (in[i - 2] + in[i - 1] + in[i] + in[i + 1] + in[i + 2]) / 5.0;				}				out[N - 2] = (4.0 * in[N - 1] + 3.0 * in[N - 2] + 2 * in[N - 3] + in[N - 4]) / 10.0;				out[N - 1] = (3.0 * in[N - 1] + 2.0 * in[N - 2] + in[N - 3] - in[N - 5]) / 5.0;			}			for (int i = 0; i < N; i++)			{				wordOut[i] = (WORD)out[i];			}		}	}	COTSImageProcess::COTSImageProcess()	{	}	COTSImageProcess::~COTSImageProcess()	{	}	// use verticl line of 3 pixel to erode a image	void COTSImageProcess::BErodeVertical3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y, wcounts;		if (rows <= 2 || columns <= 2)return;		// top line		for (x = 0; x < columns; x++)		{			*(target + x) = 0;		}		// bottom line		for (x = 0; x < columns; x++)		{			*(target + (DWORD)(rows - 1)*columns + x) = 0;		}		for (y = 1; y<rows - 1; y++)		{			for (x = 0; x<columns; x++)			{				if (*(source + (DWORD)y*columns + x) == 0)				{					*(target + (DWORD)y*columns + x) = 0;					continue;				}				wcounts = 0;				if (*(source + (DWORD)(y - 1)*columns + x) == 255)				{					wcounts++;				}				if (*(source + (DWORD)(y + 1)*columns + x) == 255)				{					wcounts++;				}				if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;				else *(target + (DWORD)y*columns + x) = 0;			}		}	}	// use left 45 degree line of 3 pixel to erode a image	void COTSImageProcess::BErodeLeft45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y, wcounts;		if (rows <= 2 || columns <= 2)return;		// top line		for (x = 0; x < columns; x++)		{			*(target + x) = 0;		}		// bottom line		for (x = 0; x < columns; x++)		{			*(target + (DWORD)(rows - 1)*columns + x) = 0;		}		// left line		for (y = 0; y<rows; y++)		{			*(target + (DWORD)y*columns) = 0;		}		// right line		for (y = 0; y<rows; y++)		{			*(target + (DWORD)y*columns + columns - 1) = 0;		}		for (y = 1; y < rows - 1; y++)		{			for (x = 1; x < columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) == 0)				{					*(target + (DWORD)y*columns + x) = 0;					continue;				}				wcounts = 0;				if (*(source + (DWORD)(y - 1)*columns + x - 1) == 255)				{					wcounts++;				}				if (*(source + (DWORD)(y + 1)*columns + x + 1) == 255)				{					wcounts++;				}				if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;				else *(target + (DWORD)y*columns + x) = 0;			}		}			}	// use horizoontal line of 3 pixel to erode a image	void COTSImageProcess::BErodeHorizontal3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y, wcounts;		if (rows <= 2 || columns <= 2)return;		// left line		for (y = 0; y<rows; y++)		{			*(target + (DWORD)y*columns) = 0;		}		// right line		for (y = 0; y<rows; y++)		{			*(target + (DWORD)y*columns + columns - 1) = 0;		}		for (y = 0; y<rows; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) == 0)				{					*(target + (DWORD)y*columns + x) = 0;					continue;				}				wcounts = 0;				if (*(source + (DWORD)y*columns + x - 1) == 255)				{					wcounts++;				}				if (*(source + (DWORD)y*columns + x + 1) == 255)				{					wcounts++;				}				if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;				else *(target + (DWORD)y*columns + x) = 0;			}		}	}	// use right 45 degree line of 3 pixel to erode a image	void COTSImageProcess::BErodeRight45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y, wcounts;		if (rows <= 2 || columns <= 2)return;		// top line		for (x = 0; x < columns; x++)		{			*(target + x) = 0;		}		// bottom line		for (x = 0; x < columns; x++)		{			*(target + (DWORD)(rows - 1)*columns + x) = 0;		}		// left line		for (y = 0; y<rows; y++)		{			*(target + (DWORD)y*columns) = 0;		}		// right line		for (y = 0; y<rows; y++)		{			*(target + (DWORD)y*columns + columns - 1) = 0;		}		for (y = 1; y<rows - 1; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) == 0)				{					*(target + (DWORD)y*columns + x) = 0;					continue;				}				wcounts = 0;				if (*(source + (DWORD)(y - 1)*columns + x + 1) == 255)				{					wcounts++;				}				if (*(source + (DWORD)(y + 1)*columns + x - 1) == 255)				{					wcounts++;				}				if (wcounts == 2) *(target + (DWORD)y*columns + x) = 255;				else *(target + (DWORD)y*columns + x) = 0;			}		}		}	void COTSImageProcess::BDilateVertical3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y;		if (rows <= 2 || columns <= 2)return;		// top line		for (x = 0; x<columns; x++)		{			if (*(source + x) != 0)			{				*(target + x) = 0xff;			}		}		// bottom line		for (x = 0; x<columns; x++)		{			if (*(source + (DWORD)(rows - 1)*columns + x) != 0)			{				*(target + (DWORD)(rows - 1)*columns + x) = 0xff;			}		}		for (y = 1; y<rows - 1; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) != 0)				{					*(target + (DWORD)y*columns + x) = 0xff;					*(target + (DWORD)(y - 1)*columns + x) = 255;					*(target + (DWORD)(y + 1)*columns + x) = 255;				}				else *(target + (DWORD)y*columns + x) = 0;			}		}	}	void COTSImageProcess::BDilateLeft45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y;		if (rows <= 2 || columns <= 2)return;		// top line		for (x = 0; x<columns; x++)		{			if (*(source + x) != 0)			{				*(target + x) = 0xff;			}		}		// bottom line		for (x = 0; x<columns; x++)		{			if (*(source + (DWORD)(rows - 1)*columns + x) != 0)			{				*(target + (DWORD)(rows - 1)*columns + x) = 0xff;			}		}		// left line		for (y = 0; y<rows; y++)		{			if (*(source + (DWORD)y*columns) != 0)			{				*(target + (DWORD)y*columns) = 0xff;			}		}		// right line		for (y = 0; y<rows; y++)		{			if (*(source + (DWORD)y*columns + columns - 1) != 0)			{				*(target + (DWORD)y*columns + columns - 1) = 0xff;			}		}		for (y = 1; y<rows - 1; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) != 0)				{					*(target + (DWORD)y*columns + x) = 0xff;					*(target + (DWORD)(y - 1)*columns + x - 1) = 255;					*(target + (DWORD)(y + 1)*columns + x + 1) = 255;				}				else *(target + (DWORD)y*columns + x) = 0;			}		}	}	void COTSImageProcess::BDilateHorizontal3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y;		if (rows <= 2 || columns <= 2)return;		// left line		for (y = 0; y<rows; y++)		{			if (*(source + (DWORD)y*columns) != 0)			{				*(target + (DWORD)y*columns) = 0xff;			}		}		// right line		for (y = 0; y<rows; y++)		{			if (*(source + (DWORD)y*columns + columns - 1) != 0)			{				*(target + (DWORD)y*columns + columns - 1) = 0xff;			}		}		for (y = 1; y<rows - 1; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) != 0)				{					*(target + (DWORD)y*columns + x) = 0xff;					*(target + (DWORD)y*columns + x - 1) = 255;					*(target + (DWORD)y*columns + x + 1) = 255;				}				else *(target + (DWORD)y*columns + x) = 0;			}		}	}	void COTSImageProcess::BDilateRight45Degree3(LPBYTE source, LPBYTE target, WORD rows, WORD columns)	{		WORD x, y;		if (rows <= 2 || columns <= 2)return;		// top line		for (x = 0; x<columns; x++)		{			if (*(source + x) != 0)			{				*(target + x) = 0xff;			}		}		// bottom line		for (x = 0; x<columns; x++)		{			if (*(source + (DWORD)(rows - 1)*columns + x) != 0)			{				*(target + (DWORD)(rows - 1)*columns + x) = 0xff;			}		}		// left line		for (y = 0; y<rows; y++)		{			if (*(source + (DWORD)y*columns) != 0)			{				*(target + (DWORD)y*columns) = 0xff;			}		}		// right line		for (y = 0; y<rows; y++)		{			if (*(source + (DWORD)y*columns + columns - 1) != 0)			{				*(target + (DWORD)y*columns + columns - 1) = 0xff;			}		}		for (y = 1; y<rows - 1; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) != 0)				{					*(target + (DWORD)y*columns + x) = 0xff;					*(target + (DWORD)(y - 1)*columns + x + 1) = 255;					*(target + (DWORD)(y + 1)*columns + x - 1) = 255;				}				else *(target + (DWORD)y*columns + x) = 0;			}		}	}	void COTSImageProcess::BErode3(LPBYTE source, LPBYTE target, WORD wDegree, WORD rows, WORD columns)	{		WORD x, y, i, j, wcounts;		if (rows == 1 || columns == 1)return;		for (y = 1; y<rows - 1; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) == 0)				{					*(target + (DWORD)y*columns + x) = 0;					continue;				}				wcounts = 0;				for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)				{					for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)					{						if (*(source + (DWORD)i*columns + j) == 0)						{							wcounts++;						}					}				}				if (wcounts >= wDegree) *(target + (DWORD)y*columns + x) = 0;				else *(target + (DWORD)y*columns + x) = 0xff;			}		}		// top line		for (x = 1; x<columns - (WORD)1; x++)		{			if (*(source + x) == 0)			{				*(target + x) = 0;				continue;			}			wcounts = 0;			for (i = 0; i <= 1; i++)			{				for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)				{					if (*(source + (DWORD)i*columns + j) == 0) wcounts++;				}			}			if (wcounts >= wDegree * 5 / 8) *(target + x) = 0;			else *(target + x) = 0xff;		}		// bottom line		for (x = 1; x<columns - 1; x++)		{			if (*(source + (DWORD)(rows - 1)*columns + x) == 0)			{				*(target + (DWORD)(rows - 1)*columns + x) = 0;				continue;			}			wcounts = 0;			for (i = (WORD)(rows - 2); i <= (WORD)(rows - 1); i++)			{				for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)				{					if (*(source + (DWORD)i*columns + j) == 0) wcounts++;				}			}			if (wcounts >= wDegree * 5 / 8) *(target + (DWORD)(rows - 1)*columns + x) = 0;			else *(target + (DWORD)(rows - 1)*columns + x) = 0xff;		}		// left line		for (y = 1; y<rows - 1; y++)		{			if (*(source + (DWORD)y*columns) == 0)			{				*(target + (DWORD)y*columns) = 0;				continue;			}			wcounts = 0;			for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)			{				for (j = 0; j <= 1; j++)				{					if (*(source + (DWORD)i*columns + j) == 0) wcounts++;				}			}			if (wcounts >= wDegree * 5 / 8) *(target + (DWORD)y*columns) = 0;			else *(target + (DWORD)y*columns) = 0xff;		}		// right line		for (y = 1; y<rows - 1; y++)		{			if (*(source + (DWORD)y*columns + columns - 1) == 0)			{				*(target + (DWORD)y*columns + columns - 1) = 0;				continue;			}			wcounts = 0;			for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)			{				for (j = (WORD)(columns - 2); j <= (WORD)(columns - 1); j++)				{					if (*(source + (DWORD)i*columns + j) == 0) wcounts++;				}			}			if (wcounts >= wDegree * 5 / 8) *(target + (DWORD)y*columns + columns - 1) = 0;			else *(target + (DWORD)y*columns + columns - 1) = 0xff;		}		return;	}	void COTSImageProcess::BDilate3(LPBYTE source, LPBYTE target, WORD wDegree, WORD rows, WORD columns)	{		WORD x, y, i, j, wcounts;		for (y = 1; y<rows - 1; y++)		{			for (x = 1; x<columns - 1; x++)			{				if (*(source + (DWORD)y*columns + x) != 0)				{					*(target + (DWORD)y*columns + x) = 0xff;					continue;				}				wcounts = 0;				for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)				{					for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)					{						if (*(source + (DWORD)i*columns + j) != 0)	wcounts++;					}				}				if (wcounts >= wDegree) *(target + (DWORD)y*columns + x) = 0xff;				else *(target + (DWORD)y*columns + x) = 0;			}		}		// top line		for (x = 1; x<columns - 1; x++)		{			if (*(source + x) != 0)			{				*(target + x) = 0xff;				continue;			}			wcounts = 0;			for (i = 0; i <= 1; i++)			{				for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)				{					if (*(source + (DWORD)i*columns + j) != 0) wcounts++;				}			}			if (wcounts >= wDegree * 5 / 8)	// but does not mater, as we have border of 2 now			{				*(target + x) = 0xff;			}			else { *(target + x) = 0; }		}		// bottom line		for (x = 1; x<columns - 1; x++)		{			if (*(source + (DWORD)(rows - 1)*columns + x) != 0)			{				*(target + (DWORD)(rows - 1)*columns + x) = 0xff;				continue;			}			wcounts = 0;			for (i = (WORD)(rows - 2); i <= (WORD)(rows - 1); i++)			{				for (j = (WORD)(x - 1); j <= (WORD)(x + 1); j++)				{					if (*(source + (DWORD)i*columns + j) != 0) wcounts++;				}			}			if (wcounts > wDegree * 5 / 8)			{				*(target + (DWORD)(rows - 1)*columns + x) = 0xff;			}			else			{				*(target + (DWORD)(rows - 1)*columns + x) = 0;			}		}		// left line		for (y = 1; y<rows - 1; y++)		{			if (*(source + (DWORD)y*columns) != 0)			{				*(target + (DWORD)y*columns) = 0xff;				continue;			}			wcounts = 0;			for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)			{				for (j = 0; j <= (WORD)1; j++)				{					if (*(source + (DWORD)i*columns + j) != 0) wcounts++;				}			}			if (wcounts >= wDegree * 5 / 8)			{				*(target + (DWORD)y*columns) = 0xff;			}			else			{				*(target + (DWORD)y*columns) = 0;			}		}		// right line		for (y = 1; y<rows - 1; y++)		{			if (*(source + (DWORD)y*columns + columns - 1) != 0)			{				*(target + (DWORD)y*columns + columns - 1) = 0xff;				continue;			}			wcounts = 0;			for (i = (WORD)(y - 1); i <= (WORD)(y + 1); i++)			{				for (j = (WORD)(columns - 2); j <= (WORD)(columns - 1); j++)				{					if (*(source + (DWORD)i*columns + j) != 0) wcounts++;				}			}			if (wcounts >= wDegree * 5 / 8)			{				*(target + (DWORD)y*columns + columns - 1) = 0xff;			}			else			{				*(target + (DWORD)y*columns + columns - 1) = 0;			}		}		// four cornor points treated separately here		// top-left		if (*(source) != 0)		{			*target = 0xff;		}		else		{			wcounts = 0;			if (*(source + 1) != 0) wcounts++;			if (*(source + columns) != 0) wcounts++;			if (*(source + columns + 1) != 0) wcounts++;			//        if (wcounts >= wDegree*3/8)  // this is a bug here - interger division			if (wcounts * 8 >= wDegree * 3)			{				*target = 0xff;			}			else			{				*target = 0;			}		}		//top-right		if (*(source + columns - 1) != 0)		{			*(target + columns - 1) = 0xff;		}		else		{			wcounts = 0;			if (*(source + columns - 2) != 0) wcounts++;			if (*(source + columns * 2 - 1) != 0) wcounts++;			if (*(source + columns * 2 - 2) != 0) wcounts++;			//        if (wcounts >= wDegree*3/8)  // this is a bug here - interger division			if (wcounts * 8 >= wDegree * 3)			{				*(target + columns - 1) = 0xff;			}			else			{				*(target + columns - 1) = 0;			}		}		//bottom-left		if (*(source + (DWORD)columns * (rows - 1)) != 0)		{			*(target + (DWORD)columns * (rows - 1)) = 0xff;		}		else		{			wcounts = 0;			if (*(source + (DWORD)columns * (rows - 1) + 1) != 0) wcounts++;			if (*(source + (DWORD)columns * (rows - 2)) != 0) wcounts++;			if (*(source + (DWORD)columns * (rows - 2) + 1) != 0) wcounts++;			//        if (wcounts >= wDegree*3/8)  // this is a bug here - interger division			if (wcounts * 8 >= wDegree * 3)			{				*(target + (DWORD)columns * (rows - 1)) = 0xff;			}			else			{				*(target + (DWORD)columns * (rows - 1)) = 0;			}		}		//bottom-right		if (*(source + (DWORD)columns * rows - 1) != 0)		{			*(target + (DWORD)columns * rows - 1) = 0xff;		}		else		{			wcounts = 0;			if (*(source + (DWORD)columns * rows - 2) != 0) wcounts++;			if (*(source + (DWORD)columns * (rows - 1) - 2) != 0) wcounts++;			if (*(source + (DWORD)columns * (rows - 1) - 1) != 0) wcounts++;			//        if (wcounts >= wDegree*3/8)  // this is a bug here - interger division			if (wcounts * 8 >= wDegree * 3)			{				*(target + (DWORD)columns * rows - 1) = 0xff;			}			else			{				*(target + (DWORD)columns * rows - 1) = 0;			}		}		return;	}	// ReZoom the picture with re-magnification 	BOOL COTSImageProcess::ReZoom(CString InPutPath, CString OutPutPath)	{		Mat cvSrcImg;		string strInputPath;		strInputPath = CStringA(InPutPath);		// Pictures loop in folder		std::vector<cv::String> ImageFolder;		cv::glob(strInputPath, ImageFolder);		if (ImageFolder.size() == 0)		{			return FALSE;		}		for (unsigned int nImgNum = 0; nImgNum < ImageFolder.size(); ++nImgNum) {			cvSrcImg = cv::imread(ImageFolder[nImgNum], CV_LOAD_IMAGE_GRAYSCALE);			// Image convolution operation				//// convolution kernel			float kernel[] = { -1,  -1 , -1,  -1 , 0, -1,  -1 ,  -1 , -1 };			cv::Mat ker = cv::Mat(nImage_Size, nImage_Size, CV_32F, &kernel);			cv::Mat cvDstImg = cv::Mat(cvSrcImg.size(), cvSrcImg.type());			// anchor of the kernel			cv::Point anchor(-1, -1);			cv::filter2D(cvSrcImg, cvDstImg, CV_32F, ker, anchor, delta, cv::THRESH_TRUNC);			// Maximum Pixel Value			cvDstImg = abs(cvDstImg);			double minVal, maxVal;			minMaxLoc(cvDstImg, &minVal, &maxVal);			// Grayscale image			int nReduce;			Mat onesImg = Mat::ones(cvDstImg.rows, cvDstImg.cols, CV_32F) * (int)minVal;			absdiff(cvDstImg, onesImg, cvDstImg);			nReduce = (int)maxVal - minVal;			cvDstImg = cvDstImg * nBlackColor / nReduce;			// Output image convert data to int			cvDstImg.convertTo(cvDstImg, CV_8U);			// Process the picture to 128 pixels			resize(cvDstImg, cvDstImg, Size(nPictureSize, nPictureSize));			threshold(cvDstImg, cvDstImg, nProcessParam, nBlackColor, CV_THRESH_BINARY);			string strOutPutPath;			strOutPutPath = CStringA(OutPutPath);			imwrite(strOutPutPath , cvDstImg);		}		return TRUE;	}	BOOL COTSImageProcess::RemoveBSEImageBG(CBSEImgPtr m_pBSEImg, COTSImageProcessParamPtr a_pImgProcessParam,COTSFieldDataPtr m_pFieldData)	{		ASSERT(m_pFieldData);		if (!m_pFieldData)		{			LogErrorTrace(__FILE__, __LINE__, _T("RemoveBSEImageBG: there is no field data"));			return FALSE;		}		ASSERT(m_pBSEImg);		if (!m_pBSEImg)		{			LogErrorTrace(__FILE__, __LINE__, _T("RemoveBSEImageBG: there is no image data"));			return FALSE;		}		ASSERT(a_pImgProcessParam);		if (!a_pImgProcessParam)		{			LogErrorTrace(__FILE__, __LINE__, _T("RemoveBSEImageBG: there is no image process data"));			return FALSE;		}		int nWidthImg = m_pBSEImg->GetWidth();		int nHeightImg = m_pBSEImg->GetHeight();		m_pFieldData->Width = nWidthImg;		m_pFieldData->Height = nHeightImg;		long nImgSize = nWidthImg * nHeightImg;						BYTE* pSrcImg = m_pBSEImg->GetImageDataPointer();		BYTE* pTempImg = new BYTE[nImgSize];				CRect r = CRect(0, 0, nWidthImg, nHeightImg);				CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));		long nNumParticle = 0;		RemoveBackGround(m_pBSEImg, a_pImgProcessParam, imgNoBGBinary,nNumParticle);					BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();							long nPtStart = a_pImgProcessParam->GetParticleGray().GetStart();		long nPtEnd = a_pImgProcessParam->GetParticleGray().GetEnd();		if (nNumParticle == 0)		{			COTSParticleList listParticleEmpty;			listParticleEmpty.clear();			m_pFieldData->SetParticleList(listParticleEmpty);				}		else		{						// get the area image						Mat blurImg;			Mat srcImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);						//medianBlur(srcImg, blurImg, 3);//smooth the edge			COTSParticleList listParticleOut;			if (!GetParticles(0,0,nWidthImg, nHeightImg, srcImg.data, listParticleOut))			{				COTSParticleList listParticleEmpty;				listParticleEmpty.clear();				m_pFieldData->SetParticleList(listParticleEmpty);							}						// form a image only have particles on			COTSSegmentsList listImage;			for (auto pParticle : listParticleOut)			{				COTSFeaturePtr pFeature = pParticle->GetFeature();				COTSSegmentsList listSegment = pFeature->GetSegmentsList();				long nPixelNum = 0;				long nPixelAll = 0;				int nStartS = 0;				int nHeightS = 0;				int nLengthS = 0;				for (auto pSegment : listSegment)				{					// update image list					COTSSegmentPtr pSegNew = COTSSegmentPtr(new COTSSegment(*pSegment.get()));					listImage.push_back(pSegNew);					// get particle average gray					nStartS = pSegment->GetStart();					nHeightS = pSegment->GetHeight();					nLengthS = pSegment->GetLength();					nPixelNum += (long)nLengthS;					if (nHeightS > nHeightImg)					{						LogErrorTrace(__FILE__, __LINE__, _T("seg height is wrong."));						return FALSE;					}					if ((nStartS + nLengthS - 1) > nWidthImg)					{						LogErrorTrace(__FILE__, __LINE__, _T("seg starst and length is wrong."));						return FALSE;					}					for (unsigned int i = 0; i < nLengthS; i++)					{						if ((nStartS + i) > nWidthImg)						{							LogErrorTrace(__FILE__, __LINE__, _T("seg start is wrong."));							return FALSE;						}						else if (nHeightS > nHeightImg)						{							LogErrorTrace(__FILE__, __LINE__, _T("seg height is wrong."));							return FALSE;						}						long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);						nPixelAll += nValueTemp;					}				}				BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);				pParticle->SetAveGray(nAveGray);				pParticle->SetActualArea(nPixelNum);			}			m_pFieldData->SetParticleList(listParticleOut);		}				delete[]pTempImg;		return TRUE;			}	BOOL COTSImageProcess::RemoveBGByFindContour(CBSEImgPtr m_pBSEImg, COTSImageProcessParamPtr a_pImageProcessParam, COTSFieldDataPtr m_pFieldData)	{		ASSERT(m_pFieldData);		ASSERT(m_pBSEImg);			ASSERT(a_pImageProcessParam);			int nWidthImg = m_pBSEImg->GetWidth();		int nHeightImg = m_pBSEImg->GetHeight();		m_pFieldData->Width = nWidthImg;		m_pFieldData->Height = nHeightImg;		long nImgSize = nWidthImg * nHeightImg;		BYTE* pSrcImg = m_pBSEImg->GetImageDataPointer();		BYTE* pTempImg = new BYTE[nImgSize];		CRect r = CRect(0, 0, nWidthImg, nHeightImg);		CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));		long nNumParticle = 0;		RemoveBackGround(m_pBSEImg, a_pImageProcessParam, imgNoBGBinary, nNumParticle);		BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();		long nPtStart = a_pImageProcessParam->GetParticleGray().GetStart();		long nPtEnd = a_pImageProcessParam->GetParticleGray().GetEnd();		if (nNumParticle == 0)		{			COTSParticleList listParticleEmpty;			listParticleEmpty.clear();			m_pFieldData->SetParticleList(listParticleEmpty);		}		else		{			// get the area image				Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);					vector<vector<Point>>contours;						findContours(cvcopyImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);			COTSParticleList listParticleOut;			for (size_t i = 0; i < contours.size(); i++)			{								Rect rectMax = boundingRect(contours[i]);				Mat  rectROI = cvcopyImg(rectMax).clone();				//exclude the point which  intersect into this bounding box but is not in this contour.				for (int nX = 0; nX < rectROI.rows; nX++)				{					for (int nY = 0; nY < rectROI.cols; nY++)					{						double localPos = pointPolygonTest(contours[i], Point2f(nX + rectMax.x, nY + rectMax.y), false);						if (localPos == -1)						{							rectROI.data[nX, nY] = 0;//set the value to 0,so we won't consider it when we find segment and feature in this ROI.						}					}				}				GetParticles(rectMax.x, rectMax.y, rectMax.width, rectMax.height, rectROI.data, listParticleOut);							}			// form a image only have particles on			//COTSSegmentsList listImage;			for (auto pParticle : listParticleOut)			{				COTSFeaturePtr pFeature = pParticle->GetFeature();				COTSSegmentsList listSegment = pFeature->GetSegmentsList();				long nPixelNum = 0;				long nPixelAll = 0;				int nStartS = 0;				int nHeightS = 0;				int nLengthS = 0;				for (auto pSegment : listSegment)				{					// get particle average gray					nStartS = pSegment->GetStart();					nHeightS = pSegment->GetHeight();					nLengthS = pSegment->GetLength();					nPixelNum += (long)nLengthS;					for (unsigned int i = 0; i < nLengthS; i++)					{							long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);						nPixelAll += nValueTemp;					}				}				BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);				pParticle->SetAveGray(nAveGray);				pParticle->SetActualArea(nPixelNum);			}			m_pFieldData->SetParticleList(listParticleOut);		}		delete[]pTempImg;		return TRUE;	}	BOOL COTSImageProcess::RemoveBGByCVconnectivities(CBSEImgPtr inBSEImg, COTSImageProcessParamPtr a_pImageProcessParam,double a_pixelSize,  COTSFieldDataPtr m_pFieldData)	{		ASSERT(m_pFieldData);		ASSERT(inBSEImg);		ASSERT(a_pImageProcessParam);		int nWidthImg = inBSEImg->GetWidth();		int nHeightImg = inBSEImg->GetHeight();		m_pFieldData->Width = nWidthImg;		m_pFieldData->Height = nHeightImg;		long nImgSize = nWidthImg * nHeightImg;		BYTE* pSrcImg = inBSEImg->GetImageDataPointer();		BYTE* pTempImg = new BYTE[nImgSize];		CRect r = CRect(0, 0, nWidthImg, nHeightImg);		CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));		long nNumParticle = 0;		RemoveBackGround(inBSEImg, a_pImageProcessParam, imgNoBGBinary, nNumParticle);		BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();		long nPtStart = a_pImageProcessParam->GetParticleGray().GetStart();		long nPtEnd = a_pImageProcessParam->GetParticleGray().GetEnd();		if (nNumParticle == 0)		{			COTSParticleList listParticleEmpty;			listParticleEmpty.clear();			m_pFieldData->SetParticleList(listParticleEmpty);		}		else		{			// get the area image				Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);			//Mat blurImg;			//medianBlur(cvcopyImg, blurImg, 5);//get rid of the noise point.			Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);			Mat  stats, centroids;			int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);						double rMin = a_pImageProcessParam->GetIncArea().GetStart()/2.0;			double rMax = a_pImageProcessParam->GetIncArea().GetEnd()/2.0;			double partAreaMin = rMin * rMin * 3.14159;			double partAreaMax = rMax * rMax * 3.14159;					COTSParticleList listParticleOut;			for (size_t i = 1; i < number; i++)			{				int center_x = centroids.at<double>(i, 0);				  int center_y = centroids.at<double>(i, 1);				  //矩形边框				  int x = stats.at<int>(i, CC_STAT_LEFT);				  int y = stats.at<int>(i, CC_STAT_TOP);				  int w = stats.at<int>(i, CC_STAT_WIDTH);				  int h = stats.at<int>(i, CC_STAT_HEIGHT);				  int area = stats.at<int>(i, CC_STAT_AREA);				  double actualArea = area * a_pixelSize * a_pixelSize;				  if (actualArea >= partAreaMin && actualArea < partAreaMax)				  {				 									Rect rectMax = Rect(x, y, w, h);																			Mat  rectROI = labels(rectMax).clone();					Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());					//exclude the point which  intersect into this bounding box but is not in this group.					int label = i;					for (int row = 0; row < rectROI.rows; row++)					{						for (int col = 0; col < rectROI.cols; col++)						{							int v = rectROI.at<int>(row, col);							if (v == label)							{								imageROI.at<uchar>(row, col) = 255;//set the value to 255,so we won't consider other pixel when we find segment and feature in this ROI.							}												}					}					COTSParticleList roiParts;										if (GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))					{						if (roiParts.size() > 0)						{							COTSParticlePtr roiPart = roiParts[0];//we will find only one part in the roi.							roiPart->SetXRayPos(CPoint(center_x, center_y));							CRect r = CRect(x, y, x + w, y + h);							roiPart->SetParticleRect(r);							roiPart->SetActualArea(actualArea);							roiPart->SetPixelArea(area);							listParticleOut.push_back(roiPart);						}					}														  }			}			int  nTagId;						for (auto pParticle : listParticleOut)			{				COTSFeaturePtr pFeature = pParticle->GetFeature();				COTSSegmentsList listSegment = pFeature->GetSegmentsList();				long nPixelNum = 0;				long nPixelAll = 0;				int nStartS = 0;				int nHeightS = 0;				int nLengthS = 0;				for (auto pSegment : listSegment)				{						// get particle average gray					nStartS = pSegment->GetStart();					nHeightS = pSegment->GetHeight();					nLengthS = pSegment->GetLength();					nPixelNum += (long)nLengthS;					for (unsigned int i = 0; i < nLengthS; i++)					{									long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);						nPixelAll += nValueTemp;					}				}				BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);				pParticle->SetAveGray(nAveGray);						}			m_pFieldData->SetParticleList(listParticleOut);		}		delete[]pTempImg;		return TRUE;	}	BOOL COTSImageProcess::GetParticlesBySpecialGrayRange(CBSEImgPtr a_pBSEImg, CIntRangePtr a_grayRange,CDoubleRangePtr a_diameterRange,double a_pixelSize, COTSFieldDataPtr m_pFieldData)	{		ASSERT(m_pFieldData);		ASSERT(a_pBSEImg);		ASSERT(a_grayRange);		int nWidthImg = a_pBSEImg->GetWidth();		int nHeightImg = a_pBSEImg->GetHeight();		m_pFieldData->Width = nWidthImg;		m_pFieldData->Height = nHeightImg;		long nImgSize = nWidthImg * nHeightImg;		BYTE* pSrcImg = a_pBSEImg->GetImageDataPointer();		BYTE* pTempImg = new BYTE[nImgSize];		CRect r = CRect(0, 0, nWidthImg, nHeightImg);		CBSEImgPtr imgNoBGBinary = CBSEImgPtr(new CBSEImg(r));				long nNumParticle = 0;		GetSpecialGrayRangeImage(a_pBSEImg, a_grayRange, imgNoBGBinary, nNumParticle);		BYTE* pPixel = imgNoBGBinary->GetImageDataPointer();		if (nNumParticle == 0)		{			COTSParticleList listParticleEmpty;			listParticleEmpty.clear();			m_pFieldData->SetParticleList(listParticleEmpty);				}		else		{			// get the area image			Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);					Mat labels = Mat::zeros(cvcopyImg.size(), CV_32S);			Mat  stats, centroids;			int number = connectedComponentsWithStats(cvcopyImg, labels, stats, centroids, 8, CV_32S);			double rStart = a_diameterRange->GetStart() / 2.0;			double rEnd = a_diameterRange->GetEnd() / 2.0;			double areaStart = rStart * rStart * 3.14159;			double areaEnd = rEnd * rEnd * 3.14159;			COTSParticleList listParticleOut;			for (size_t i = 1; i < number; i++)			{				int center_x = centroids.at<double>(i, 0);				int center_y = centroids.at<double>(i, 1);				//矩形边框				int x = stats.at<int>(i, CC_STAT_LEFT);				int y = stats.at<int>(i, CC_STAT_TOP);				int w = stats.at<int>(i, CC_STAT_WIDTH);				int h = stats.at<int>(i, CC_STAT_HEIGHT);				int area = stats.at<int>(i, CC_STAT_AREA);				double actualArea = area * a_pixelSize * a_pixelSize;								if (actualArea >= areaStart && actualArea < areaEnd)				{					Rect rectMax = Rect(x, y, w, h);					Mat  rectROI = labels(rectMax).clone();					Mat imageROI = Mat::zeros(rectMax.size(), cvcopyImg.type());					//exclude the point which  intersect into this bounding box but is not in this group.					int label = i;					for (int row = 0; row < rectROI.rows; row++)					{						for (int col = 0; col < rectROI.cols; col++)						{							int v = rectROI.at<int>(row, col);							if (v == label)							{								imageROI.at<uchar>(row, col) = 255;							}						}					}					COTSParticleList roiParts;					if (!GetOneParticleFromROI(rectMax.x, rectMax.y, rectMax.width, rectMax.height, imageROI.data, roiParts))					{						continue;					}					if (roiParts.size() > 0)					{						COTSParticlePtr roiPart = roiParts[0];						roiPart->SetXRayPos(CPoint(center_x, center_y));						CRect r = CRect(x, y, x + w, y + h);						roiPart->SetParticleRect(r);						roiPart->SetActualArea(actualArea);						roiPart->SetPixelArea(area);						listParticleOut.push_back(roiPart);					}				     														}							}			// form a image only have particles on			//COTSSegmentsList listImage;						for (auto pParticle : listParticleOut)			{				int area = pParticle->GetActualArea();				double pActualArea = area ;								COTSFeaturePtr pFeature = pParticle->GetFeature();					COTSSegmentsList listSegment = pFeature->GetSegmentsList();					long nPixelNum = 0;					long nPixelAll = 0;					int nStartS = 0;					int nHeightS = 0;					int nLengthS = 0;					for (auto pSegment : listSegment)					{						// get particle average gray						nStartS = pSegment->GetStart();						nHeightS = pSegment->GetHeight();						nLengthS = pSegment->GetLength();						nPixelNum += (long)nLengthS;						for (unsigned int i = 0; i < nLengthS; i++)						{							long nValueTemp = (long)*(pSrcImg + nHeightS * nWidthImg + nStartS + i);							nPixelAll += nValueTemp;						}					}					BYTE nAveGray = (BYTE)(nPixelAll / nPixelNum);					pParticle->SetAveGray(nAveGray);			}			m_pFieldData->SetParticleList(listParticleOut);		}		delete[]pTempImg;		return TRUE;	}	CIntRangePtr COTSImageProcess::CalBackground(CBSEImgPtr m_pBSEImg)	{		CIntRangePtr pBackground = CIntRangePtr(new CIntRange());		WORD nBSEChart[MAXBYTE];		//1. get chart data		m_pBSEImg->SetChartData();		linearSmooth5(m_pBSEImg->GetBSEChart(), nBSEChart,MAXBYTE);		//2. get down edge				int nLengthEdge = MAXBYTE + 2;		WORD n_aBSEChart[MAXBYTE + 2];		memset(n_aBSEChart, 0, sizeof(WORD) * nLengthEdge);		std::map<long, std::vector <int>> upEdgeSeries;		std::map<long, std::vector<int>> downEdgeSeries;		std::vector<int> currentUpSeries;		std::vector<int> currentDownSeries;		// make sure the wave begin with up edge and end with down edge		n_aBSEChart[0] = 0;		n_aBSEChart[nLengthEdge - 1] = 0;		memcpy(&n_aBSEChart[1], &nBSEChart, sizeof(WORD) * MAXBYTE);		int nLengthCom = MAXBYTE + 1;		// up edge		for (int i = 0; i < nLengthCom; i++)		{			if (n_aBSEChart[i] <= n_aBSEChart[i + 1])			{				if (currentDownSeries.size() > 0)				{					int seriesSize = currentDownSeries.size();					long area = 0;					for (int i = 0; i < seriesSize; i++)					{						area = area + n_aBSEChart[currentDownSeries[i]];					}					downEdgeSeries[area] = currentDownSeries;					currentDownSeries.clear();				}				currentUpSeries.push_back(i);			}			else			{				if (currentUpSeries.size() > 0)				{					int seriesSize = currentUpSeries.size();					long area = 0;					for (int i = 0; i < seriesSize; i++)					{						area = area + n_aBSEChart[currentUpSeries[i]];					}					upEdgeSeries[area] = currentUpSeries;					currentUpSeries.clear();				}				currentDownSeries.push_back(i);			}		}		CIntRangePtr pRangeFirst = CIntRangePtr(new CIntRange());		if (upEdgeSeries.size() > 0)		{			pRangeFirst->SetStart((upEdgeSeries.rbegin())->second[0]);		}		if (downEdgeSeries.size() > 0)		{			auto s = downEdgeSeries.rbegin()->second;			pRangeFirst->SetEnd((long)(s[s.size() - 1]));		}			return pRangeFirst;	}	void COTSImageProcess::GetSpecialGrayRangeImage(CBSEImgPtr a_pImgIn, CIntRangePtr a_SpecialGrayRange, CBSEImgPtr a_pBinImgOut, long& foundedPixelNum)	{		// the background  pixel will be 0,and the other part will be 255.		ASSERT(a_pImgIn);			int nWidthImg = a_pImgIn->GetWidth();		int nHeightImg = a_pImgIn->GetHeight();		long nImgSize = nWidthImg * nHeightImg;		BYTE* pTempImg = new BYTE[nImgSize];		BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();		BYTE* pPixel = new byte[nImgSize];		long nBGStart;		long nBGEnd;			long nNumParticle = 0;				nBGStart = a_SpecialGrayRange->GetStart();			nBGEnd = a_SpecialGrayRange->GetEnd();						// delete background 			for (unsigned int i = 0; i < nImgSize; i++)			{				if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)				{					pPixel[i] = 255;					nNumParticle++;				}				else				{					pPixel[i] = 0;									}					}					//Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);// use the medianblur method to achieve the same effect as open morphology(errod and dialate).			//pPixel = cvcopyImg.data;			COTSImageProcess::BErode3(pPixel, pTempImg, 3, nHeightImg, nWidthImg);			COTSImageProcess::BDilate3(pTempImg, pPixel, 3, nHeightImg, nWidthImg);					a_pBinImgOut->SetImageData(pPixel, nWidthImg, nHeightImg);		foundedPixelNum = nNumParticle;		delete[] pTempImg;		return;	}	void COTSImageProcess::RemoveBackGround(CBSEImgPtr a_pImgIn, COTSImageProcessParamPtr a_pImageProcessParam, CBSEImgPtr a_pBinImgOut,long& foundedPixelNum)	{		// the background  pixel will be 0,and the other part will be 255.		ASSERT(a_pImgIn);				ASSERT(a_pImageProcessParam);		int nWidthImg = a_pImgIn->GetWidth();		int nHeightImg = a_pImgIn->GetHeight();		long nImgSize = nWidthImg * nHeightImg;		BYTE* pTempImg = new BYTE[nImgSize];				BYTE* pSrcImg = a_pImgIn->GetImageDataPointer();		     BYTE* pPixel = new byte[nImgSize];					long nBGStart;		long nBGEnd;		long nPartStart;		long nPartEnd;		long nNumParticle = 0;		if (a_pImageProcessParam->GetBGRemoveType() == OTS_BGREMOVE_TYPE::MANUAL)		{			nBGStart = a_pImageProcessParam->GetBGGray().GetStart();			nBGEnd = a_pImageProcessParam->GetBGGray().GetEnd();			nPartStart = a_pImageProcessParam->GetParticleGray().GetStart();			nPartEnd = a_pImageProcessParam->GetParticleGray().GetEnd();			// delete background 			for (unsigned int i = 0; i < nImgSize; i++)			{				if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)				{					pPixel[i] = 0;				}				else				{					pPixel[i] = 255;					nNumParticle++;				}				if (pSrcImg[i]<nPartStart || pSrcImg[i]>nPartEnd)				{					pPixel[i] = 0;				}			}			COTSImageProcess::BErode3(pPixel, pTempImg, 3, nHeightImg, nWidthImg);			COTSImageProcess::BDilate3(pTempImg, pPixel, 3, nHeightImg, nWidthImg);			//Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);// use the medianblur method to achieve the same effect as open morphology(errod and dialate).			//medianBlur(cvcopyImg, cvcopyImg, 5);			//pPixel = cvcopyImg.data;					}		else		{					auto range = CalBackground(a_pImgIn);			nBGStart = range->GetStart();			nBGEnd = range->GetEnd();			switch (a_pImageProcessParam->GetAutoBGRemoveType())			{			case OTS_AUTOBGREMOVE_TYPE::DOWNWARD:				for (unsigned int i = 0; i < nImgSize; i++)				{					if (pSrcImg[i] <= nBGEnd)					{						pPixel[i] = 0;					}					else					{						pPixel[i] = 255;						nNumParticle++;					}				}				break;			case OTS_AUTOBGREMOVE_TYPE::UPWARD:				for (unsigned int i = 0; i < nImgSize; i++)				{					if (pSrcImg[i] >= nBGStart)					{						pPixel[i] = 0;					}					else					{						pPixel[i] = 255;						nNumParticle++;					}				}				break;			case OTS_AUTOBGREMOVE_TYPE::MIDDLE:				for (unsigned int i = 0; i < nImgSize; i++)				{					if (pSrcImg[i] >= nBGStart && pSrcImg[i] <= nBGEnd)					{						pPixel[i] = 0;					}					else					{						pPixel[i] = 255;						nNumParticle++;					}				}				break;			default:				break;			}			COTSImageProcess::BErode3(pPixel, pTempImg, 3, nHeightImg, nWidthImg);			COTSImageProcess::BDilate3(pTempImg, pPixel, 3, nHeightImg, nWidthImg);			/*Mat cvcopyImg = Mat(nHeightImg, nWidthImg, CV_8UC1, pPixel);			medianBlur(cvcopyImg, cvcopyImg, 5);			pPixel = cvcopyImg.data;*/		}		a_pBinImgOut->SetImageData(pPixel,nWidthImg,nHeightImg);				foundedPixelNum = nNumParticle;		delete[] pTempImg;				return ;	}	BOOL COTSImageProcess::GetParticles(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)	{		ASSERT(a_pPixel);		if (!a_pPixel)		{			return FALSE;		}		//a_listParticles.clear();		COTSParticleList findedParts;		COTSSegmentsList listSegment;		listSegment.clear();		//1. get segment line by line			if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))		{			return FALSE;		}		if ((int)listSegment.size() == 0)		{			return FALSE;		}		//2. save the temp feature		COTSFeatureList listFeature;		listFeature.clear();		if (!GetFeatureList(listSegment, listFeature))//get every feature for all the particle,the complete feature.		{			return FALSE;		}		if ((int)listFeature.size() == 0)		{			return FALSE;		}		/*COTSParticleList listParticles;		listParticles.clear();*/		if (!ChangeFeaturelist(listFeature, findedParts))		{			return FALSE;		}		for (auto f : findedParts)		{			a_listParticles.push_back(f);		}		return TRUE;	}	BOOL COTSImageProcess::GetOneParticleFromROI(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSParticleList& a_listParticles)	{		ASSERT(a_pPixel);		if (!a_pPixel)		{			return FALSE;		}		//a_listParticles.clear();		COTSParticleList findedParts;		COTSSegmentsList listSegment;		listSegment.clear();		//1. get segment line by line			if (!GetSegmentList(left, top, a_nWidth, a_nHeight, a_pPixel, listSegment))		{			return FALSE;		}		if ((int)listSegment.size() == 0)		{			return FALSE;		}		//2. save the temp feature		COTSFeatureList listFeature;		listFeature.clear();		COTSFeaturePtr fea = COTSFeaturePtr(new COTSFeature());				fea->SetSegmentsList(listSegment);				listFeature.push_back(fea);		if ((int)listFeature.size() == 0)		{			return FALSE;		}			if (!ChangeFeaturelist(listFeature, findedParts))		{			return FALSE;		}		for (auto f : findedParts)		{			a_listParticles.push_back(f);		}		return TRUE;	}	BOOL COTSImageProcess::GetSegmentList(long left, long top, long a_nWidth, long a_nHeight, const BYTE* a_pPixel, COTSSegmentsList& a_listSegments)	{		ASSERT(a_pPixel);		if (!a_pPixel)		{			//LogErrorTrace(__FILE__, __LINE__, _T("GetSegments: there is no image data"));			return FALSE;		}		long nImgSize = a_nWidth * a_nHeight;		a_listSegments.clear();		//1. get segment line by line		long nLine, nm, nn;		long nStart = 0, nLength = 0;		for (nLine = 0; nLine < a_nHeight; nLine++)		{			for (nm = 0; nm < a_nWidth; nm += (nLength + 1))			{				nLength = 0;				// get start				if (*(a_pPixel + nLine * a_nWidth + nm) != 0)				{					nStart = nm;					nLength++;					//get length					for (nn = nm + 1; nn < a_nWidth; nn++)					{						// check if segment is over, break						if (nLength != 0)						{							if (*(a_pPixel + nLine * a_nWidth + nn) == 0)								break;						}						if (*(a_pPixel + nLine * a_nWidth + nn) != 0)						{							nLength++;						}					}					// generate segment					COTSSegmentPtr pSegment = COTSSegmentPtr(new COTSSegment(nLine + top, nStart + left, nLength));					a_listSegments.push_back(pSegment);				}				else				{					continue;				}			}		}		if ((int)a_listSegments.size() == 0)		{			//LogErrorTrace(__FILE__, __LINE__, _T("no particle is found."));			return FALSE;		}		return TRUE;	}	BOOL COTSImageProcess::GetFeatureList(COTSSegmentsList& a_listSegments, COTSFeatureList& a_listFeatures)	{		COTSSegmentsList listSegmentNew;		std::map<long, COTSSegmentsList > mapOneLineSegments;		for each (auto s in a_listSegments)		{			mapOneLineSegments[s->GetHeight()].push_back(s);//sorting all the segments base on the line number.		}		std::map<long, COTSSegmentsList >::iterator lineItr = mapOneLineSegments.begin();//find the highest line		while (lineItr != mapOneLineSegments.end())		{			for (auto s = lineItr->second.begin(); s < lineItr->second.end(); )//find  one segment of this line.			{				COTSSegmentPtr bottomSeg = *s;				listSegmentNew.clear();				listSegmentNew.push_back(*s);				s = lineItr->second.erase(s);				std::map<long, COTSSegmentsList >::iterator tempItr = lineItr;				tempItr++;				for (; tempItr != mapOneLineSegments.end(); tempItr++)//find all other lines of segments				{					if (tempItr->first - bottomSeg->GetHeight() > 1)					{						break;					}					for (auto nextLineSegment = tempItr->second.begin(); nextLineSegment < tempItr->second.end();)//find next line's all segments					{						if (((*nextLineSegment)->GetStart() - (bottomSeg->GetStart() + bottomSeg->GetLength())) > 1)						{							break;						}						if (bottomSeg->UpDownConection(**nextLineSegment))						{							listSegmentNew.push_back(*nextLineSegment);							bottomSeg = *nextLineSegment;							nextLineSegment = tempItr->second.erase(nextLineSegment);							break;						}						if (tempItr->second.size() > 0)						{							nextLineSegment++;						}						else						{							break;						}					}				}				COTSFeaturePtr pFeature = COTSFeaturePtr(new COTSFeature());				pFeature->SetSegmentsList(listSegmentNew);				//check if this new feature is connected with other found feature.				COTSSegmentPtr topSeg = listSegmentNew[0];//find the toppest segment of this new feature.				COTSSegmentPtr bottomSegment = listSegmentNew[listSegmentNew.size() - 1];//find the lowest segment of this new feature.				bool haveMerged = false;				for each (auto f in a_listFeatures)				{					for (auto seg : f->GetSegmentsList())					{						if (bottomSegment->UpDownConection(*seg) || topSeg->UpDownConection(*seg))						{							COTSSegmentsList segs = f->GetSegmentsList();							for (auto s : listSegmentNew)							{								segs.push_back(s);							}							f->SetSegmentsList(segs);							haveMerged = true;							break;						}					}					if (haveMerged)					{						break;					}				}				if (!haveMerged)				{					a_listFeatures.push_back(pFeature);				}				if (lineItr->second.size() == 0)				{					break;				}			}			lineItr++;		}		return true;	}	BOOL COTSImageProcess::ChangeFeaturelist(COTSFeatureList& a_listFeatures, COTSParticleList& a_listParticle)	{		if (a_listFeatures.size() == 0)		{			return FALSE;		}		// compute Rect		for (auto pFeature : a_listFeatures)		{			COTSParticlePtr pParticle = COTSParticlePtr(new COTSParticle());			pParticle->SetFeature(pFeature);			/*if (!pParticle->CalCoverRect())			{				return FALSE;			}*/					/*COTSSegmentsList listSegment = pFeature->GetSegmentsList();			long nPixelNum = 0;			int nLengthS = 0;			for (auto pSegment : listSegment)			{				nLengthS = pSegment->GetLength();				nPixelNum += (long)nLengthS;			}						pParticle->SetArea(nPixelNum);*/			a_listParticle.push_back(pParticle);		}		if ((int)a_listParticle.size() == 0)		{			return FALSE;		}		return TRUE;	}	 BOOL COTSImageProcess::CalcuParticleImagePropertes(COTSParticlePtr a_pOTSPart, double a_PixelSize)	{			//--------- convert this particle data to image data,construct an image only with this particle.------		const int nExpand_Size = 3;		const int nWhiteColor = 0;		const int nThickness = 1;		// lineType Type of the line		const int nLineType = 8;		// get rectangle of the particle		CRect rect = a_pOTSPart->GetParticleRect();		if (a_pOTSPart->GetActualArea() < 30 * a_PixelSize)// the particle is too small that openCV can't calculate a width value of it. Then we take the upright rect of the particle as it's minArea rect.		{			double w = 0, h = 0;			w = (double)rect.Width()*a_PixelSize;			h = (double)rect.Height()*a_PixelSize;			a_pOTSPart->SetDMax(MAX(w, h));			a_pOTSPart->SetDMin(MIN(w, h));			a_pOTSPart->SetDMean((w + h) / 2);			a_pOTSPart->SetFeretDiameter((w + h) / 2);			a_pOTSPart->SetDElong(MAX(w, h));			a_pOTSPart->SetPerimeter((w+h)*2);			a_pOTSPart->SetDPerp(MIN(w, h));			a_pOTSPart->SetDInscr(MIN(w, h));			return true;		}		// calculate the particle image data size, expand 3 pixel at the edge		Mat particleImage = Mat::zeros(rect.Height() + nExpand_Size , rect.Width() + nExpand_Size , CV_8U);		// get the segment list		COTSSegmentsList listSegment = a_pOTSPart->GetFeature()->GetSegmentsList();		for (auto pSegment : listSegment)		{			int nStart = pSegment->GetStart() - rect.left + nExpand_Size;			int nEnd = pSegment->GetStart() + pSegment->GetLength() - rect.left - 1 + nExpand_Size;			int nHeight = pSegment->GetHeight() - rect.top + nExpand_Size;			line(particleImage, Point(nStart, nHeight), Point(nEnd, nHeight), Scalar(nBlackColor), nThickness, nLineType);		}			//--------abstract the contour of the particle.		Mat cvcopyImg;		medianBlur(particleImage, cvcopyImg, 5);//smooth the edge			vector<vector<Point>>contours;			findContours(cvcopyImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);		if (contours.size()==0)// the particle is too odd that openCV can't find a contour of it. Then we take the upright rect of the particle as it's minArea rect.		{			double w = 0, h = 0;			w = (double)rect.Width()*a_PixelSize;			h = (double)rect.Height()*a_PixelSize;			a_pOTSPart->SetDMax(MAX(w, h));			a_pOTSPart->SetDMin(MIN(w, h));			a_pOTSPart->SetDMean((w + h) / 2);			a_pOTSPart->SetFeretDiameter((w + h) / 2);			a_pOTSPart->SetDElong(MAX(w, h));			a_pOTSPart->SetPerimeter((w + h) * 2);			a_pOTSPart->SetDPerp(MIN(w, h));			a_pOTSPart->SetDInscr(MIN(w, h));			return true;		}		int imaxcontour = 0, imax = 0;		for (unsigned int i = 0; i < contours.size(); i++) {                  			int itmp = contourArea(contours[i]);			if (imaxcontour < itmp) {				imax = i;				imaxcontour = itmp;			}		}		vector<Point > listEdge = contours[imax];				vector<vector<Point>>Outcontours;		Outcontours.push_back(listEdge);				//---------calculate the minimium  rectangle 		auto rRect = cv::minAreaRect(listEdge);		Point2f p[4];		rRect.points(p);		int D_MIN =getDistance(p[0], p[1]);		int D_MinRecLen = 0;//minareaRect's length(the lenger side).		for (int j = 0; j <= 2; j++)		{			//line(cvContourImg, p[j], p[(j + 1) % 4], Scalar(100, 100, 0), 2);			int d = getDistance(p[j], p[j + 1]);			if (d < D_MIN)			{				D_MIN = d;			}			if (d > D_MinRecLen)			{				D_MinRecLen = d;			}		}		a_pOTSPart->SetDMin(D_MIN*a_PixelSize);		a_pOTSPart->SetOrientation(rRect.angle);		//----------calculate the perimeter		double d = arcLength(listEdge, true);		a_pOTSPart->SetPerimeter(d*a_PixelSize);		//-----------calculate the Max Diameter. Find the min enclosing circle first ,then find the two farthest circle connected point.		Point2f center; float radius;		minEnclosingCircle(listEdge, center, radius);		//circle(cvContourImg, center, radius, Scalar(100), 2);		std::vector <Point> outContour = listEdge;				std::vector <Point> rst;		for (unsigned int k = 0; k < outContour.size(); k++)		{			Point p = outContour[k];			double d = sqrt(pow((p.x - center.x), 2) + pow((p.y - center.y), 2));			if (fabs(d - radius) < 0.01)			{				rst.push_back(p);			}		}		double D_MAX = 0;		Point lineDmax[2];		for (unsigned int m = 0; m < rst.size(); m++)		{			Point p = rst[m];			for (unsigned int n = m + 1; n < rst.size(); n++)			{				Point p1 = rst[n];				double d = sqrt(powf((p.x - p1.x), 2) + powf((p.y - p1.y), 2));				if (d > D_MAX)				{					D_MAX = d;					lineDmax[0] = p;					lineDmax[1] = p1;				}			}		}		a_pOTSPart->SetDMax(D_MAX*a_PixelSize);				//--------calculate the D_PERP property using the D_MAX's two endpoints.		std::vector<Point> curve1;		std::vector<Point> curve2;		for (unsigned int i = 0; i < outContour.size(); i++)		{			Point pt = outContour[i];			bool start = false;			int clockwise = Side(lineDmax[0], lineDmax[1], pt);// devide these points into two group ,separate into the two sides.			if (clockwise > 0)			{				curve1.push_back(pt);			}			else			{				curve2.push_back(pt);			}		}		double d_perp1 = 0, d_perp2 = 0;		for (unsigned int i = 0; i < curve1.size(); i++)		{			double d = getDist_P2L(curve1[i], lineDmax[0], lineDmax[1]);			if (d > d_perp1)			{				d_perp1 = d;			}		}		for (unsigned int i = 0; i < curve2.size(); i++)		{			double d = getDist_P2L(curve2[i], lineDmax[0], lineDmax[1]);			if (d > d_perp2)			{				d_perp2 = d;			}		}		a_pOTSPart->SetDPerp((d_perp1 + d_perp2)*a_PixelSize);		//----------find the  diameter of max inscribed circle		int r;		Point inscribeCirclecenter;		FindInnerCircleInContour(outContour, inscribeCirclecenter, r);		//--------------------------------------------------------calculate the xraypos failed, expect improving later!		//CPoint xrayPos = a_pOTSPart->GetXRayPos();		//double localPos = pointPolygonTest(outContour, Point2f(xrayPos.x, xrayPos.y), false);		//if (localPos == 1 || localPos == 0)//像素点在多边形内和边缘 		//{		//			//}		//else		//{		//	a_pOTSPart->SetXRayPos(CPoint(inscribeCirclecenter.x, inscribeCirclecenter.y));		//}		//--------------------------------------------------------		//circle(cvContourImg, inscribeCirclecenter, r, Scalar(200));		a_pOTSPart->SetDInscr(r * 2 * a_PixelSize);		//---------------calculate the image other caracater: length/width  realArea/minRectangeArea etc. we can use these propertes to do forward process.		double minRectArea = D_MIN * D_MinRecLen*a_PixelSize*a_PixelSize;//最小外接矩形面积		double fillRatio = a_pOTSPart->GetActualArea() / minRectArea;//实际面积与最小外接矩形面积比,that's the fill rate.		double lengthWidthRatio;		lengthWidthRatio = (double)D_MinRecLen / D_MIN;//长宽比			 //decide if this shape is a strip shape :if the lenthWidthRatio>2 then it is. if the lengthWidthRatio<2 and  the areaRatio<0.5 then it is.		bool isStripShape = false;		double curveLength = 0;		double D_MEAN=0;		Moments mu;		mu = moments(listEdge, false);		int nx = mu.m10 / mu.m00;		int ny = mu.m01 / mu.m00;		//circle(cvcopyImg, Point(nx, ny), 1, (255), 1);		Point ptCenter = Point((int)nx, (int)ny);		if (pointPolygonTest(outContour, ptCenter, false) != 1)// the center point doesn't contain in the contour, we think it as curve shape.		{			isStripShape = true;		}		/*if (lengthWidthRatio >= 2 )// in PartA software this is true,but IncA because of the GB definition the everage feret diameter is always the mean value of all the chord.		{						isStripShape = true;		}*/				if (fillRatio <= 0.4)// only when the fill rate is very low,we think it as a curve shape,then we choose the mean width as the feret diameter.		{			isStripShape = true;		}				if (isStripShape)		{			curveLength = a_pOTSPart->GetPerimeter()/2 - a_pOTSPart->GetDInscr()/2;// thinking this particle as a strip rectangle.the width is the max inscribe circle diameter/2.			if (curveLength < D_MAX)			{				curveLength = D_MAX;			}			if (curveLength < MIN_DOUBLE_VALUE || a_pOTSPart->GetActualArea()<MIN_DOUBLE_VALUE)			{				D_MEAN = 0;			}			else			{				D_MEAN = a_pOTSPart->GetActualArea() / curveLength;			}						a_pOTSPart->SetDMean(D_MEAN*a_PixelSize);			a_pOTSPart->SetFeretDiameter(D_MEAN*a_PixelSize);			a_pOTSPart->SetDElong (curveLength*a_PixelSize);		}		else//it's a ball shape particle		{			curveLength = D_MAX;			double ftd = 0, maxD = 0, minD = 0, dratio = 0;			GetParticleAverageChord(outContour, a_PixelSize, ftd);						a_pOTSPart->SetDMean(ftd);			a_pOTSPart->SetFeretDiameter(ftd);			a_pOTSPart->SetDElong(curveLength*a_PixelSize);		}	return true;			}	BOOL COTSImageProcess::MergeBigBoundaryParticles(COTSFieldDataList allFields,double pixelSize,int scanFieldSize, CSize ResolutionSize, COTSParticleList& mergedParts)	{		COTSSegmentsList boarderSegs;		auto FldMgr = new CFieldMgr(scanFieldSize, ResolutionSize);			std::map<COTSParticle*, COTSParticleList> mapMergeParticles;//hold up all the boundary connected particles. the pair's first is also the member of these particles.		std::map<COTSParticle*, COTSSegmentsList> mapMergedSegments;//hold up all the segment's corresponding clone in the connected particles.		for (auto centerfld : allFields)		{			// find neighbor field on the left.			auto leftFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::LEFT);			if (leftFld != nullptr)			{				auto leftParts = centerfld->GetLeftBorderedBigParticles();				auto rightParts = leftFld->GetRightBorderedBigParticles();				for (auto leftp : leftParts)				{					for (auto rightp : rightParts)					{						if (leftp->IsConnected(rightp.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::LEFT))						{							if (leftp->headerParticle != NULL)							{								if (rightp->headerParticle == NULL)								{									rightp->headerParticle = leftp->headerParticle;									mapMergeParticles[leftp->headerParticle].push_back(rightp);								}							}							else							{								if (rightp->headerParticle != NULL)								{									leftp->headerParticle = rightp.get();									mapMergeParticles[rightp.get()].push_back(leftp);								}								else								{									leftp->headerParticle = leftp.get();									rightp->headerParticle = leftp.get();									mapMergeParticles[leftp.get()].push_back(rightp);								}							}						}					}				}			}			//find neighbor field on the upward			auto upFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::UP);			if (upFld != nullptr)			{				auto upParts = centerfld->GetTopBorderedBigParticles();				auto downParts = upFld->GetBottomBorderedBigParticles();				for (auto upprt : upParts)				{					for (auto downprt : downParts)					{						if (upprt->IsConnected(downprt.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::UP))						{							if (upprt->headerParticle != NULL)							{								if (downprt->headerParticle == NULL)								{									downprt->headerParticle = upprt->headerParticle;									mapMergeParticles[upprt->headerParticle].push_back(downprt);								}							}							else							{								if (downprt->headerParticle != NULL)								{									upprt->headerParticle = downprt->headerParticle;									mapMergeParticles[downprt.get()].push_back(upprt);								}								else								{									upprt->headerParticle = upprt.get();									downprt->headerParticle = upprt.get();									mapMergeParticles[upprt.get()].push_back(downprt);								}							}						}					}				}			}			//find neighbor field on the downward.			auto downFld = FldMgr->FindNeighborField(allFields, centerfld,SORTING_DIRECTION::DOWN);			if (downFld != nullptr)			{				auto downParts = centerfld->GetBottomBorderedBigParticles();				auto upParts = downFld->GetTopBorderedBigParticles();				for (auto downprt : downParts)				{					for (auto upprt : upParts)					{						if (downprt->IsConnected(upprt.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::DOWN))						{							if (downprt->headerParticle != NULL)							{								if (upprt->headerParticle == NULL)								{									upprt->headerParticle = downprt->headerParticle;									mapMergeParticles[downprt->headerParticle].push_back(upprt);								}							}							else							{								if (upprt->headerParticle != NULL)								{									downprt->headerParticle = upprt->headerParticle;									mapMergeParticles[upprt->headerParticle].push_back(downprt);								}								else								{									downprt->headerParticle = downprt.get();									upprt->headerParticle = downprt.get();									mapMergeParticles[downprt.get()].push_back(upprt);								}							}						}					}				}			}			//find neighbor field on the right.			auto rightFld = FldMgr->FindNeighborField(allFields, centerfld, SORTING_DIRECTION::RIGHT);			if (rightFld != nullptr)			{				auto rightParts = centerfld->GetRightBorderedBigParticles();				auto leftParts = rightFld->GetLeftBorderedBigParticles();				for (auto rightprt : rightParts)				{					for (auto leftprt : leftParts)					{						if (rightprt->IsConnected(leftprt.get(), centerfld->Width, centerfld->Height, (int)SORTING_DIRECTION::RIGHT))						{							if (rightprt->headerParticle != NULL)							{								if (leftprt->headerParticle == NULL)								{									leftprt->headerParticle = rightprt->headerParticle;									mapMergeParticles[rightprt->headerParticle].push_back(leftprt);								}							}							else							{								if (leftprt->headerParticle != NULL)								{									rightprt->headerParticle = leftprt->headerParticle;									mapMergeParticles[leftprt->headerParticle].push_back(rightprt);								}								else								{									rightprt->headerParticle = rightprt.get();									leftprt->headerParticle = rightprt.get();									mapMergeParticles[rightprt.get()].push_back(leftprt);								}							}						}					}				}			}		}		static int partTagId;		for (auto pair : mapMergeParticles)		{			struct EleAreaPercentage			{				EleAreaPercentage(double p, CElementChemistryPtr e)				{					areaPercentage = p;					eleData = e;				}				double areaPercentage;				CElementChemistryPtr eleData;			};			auto newPart = COTSParticlePtr(new COTSParticle());			COTSSegmentsList newSegs;			auto p = pair.first;			newPart->SetAbsolutePos(p->GetAbsolutPos());						//firstly,we sum up all the merged particles's area and get the represent string.			std::string partsStr = std::to_string(p->GetFieldId()) + ":" + std::to_string(p->GetAnalysisId());			double allPartArea = p->GetActualArea();//Get the first particle's area.			for (auto other : pair.second)// Get the total area of all these particles for  the use of ele calcu.			{				partsStr += "," + std::to_string(other->GetFieldId()) + ":" + std::to_string(other->GetAnalysisId());//Get the subparticles string such as "1:1,2:1" etc.				allPartArea += other->GetActualArea();//Get other particle's area			}			// calculate all the new segment's position.			std::vector <COTSParticle*> allSubParts;			allSubParts.push_back(p);			for (auto other : pair.second)// Get the total area of all these particles for  the use of ele calcu.			{				allSubParts.push_back(other.get());			}			for (auto subp : allSubParts)			{				int fid = subp->GetFieldId();				CPoint myFldPos;				for (auto f : allFields)//find  this particle's filed.				{					if (f->GetId() == fid)					{						myFldPos = f->GetPosition();					}				}				int fldWidth = allFields[0]->Width;				int fldHeight = allFields[0]->Height;				CPoint fldLeftUpPos = CPoint(myFldPos.x + fldWidth / 2 , myFldPos.y + fldHeight / 2 );				for (auto s : subp->GetFeature()->GetSegmentsList())				{					COTSSegmentPtr newseg = COTSSegmentPtr(new COTSSegment());					newseg->SetStart(s->GetStart()  + fldLeftUpPos.x);					newseg->SetHeight((0 - s->GetHeight()) + fldLeftUpPos.y);//the coordinate system of segment in a field is different with the OTS coordinate system.OTS system's y axis is upward positive ,yet the field is downward positive.					newseg->SetLength(s->GetLength());					newSegs.push_back(newseg);				}			}			COTSFeaturePtr newFeature = COTSFeaturePtr(new COTSFeature());			newFeature->SetSegmentsList(newSegs);			newPart->SetFeature(newFeature);			newPart->CalCoverRect();			//second, we get all the element data and their  area percentage .			std::map<std::string, std::vector<EleAreaPercentage>> mapEleData;			CPosXrayPtr pXray1 = p->GetXrayInfo();			if (pXray1 != nullptr)			{				for (auto ele : pXray1->GetElementQuantifyData())				{					mapEleData[ele->GetName().GetBuffer()].push_back(EleAreaPercentage(p->GetActualArea() / allPartArea, ele));				}			}						for (auto other : pair.second)			{				auto otherXray = other->GetXrayInfo();				if (otherXray != nullptr)				{					for (auto eledata : otherXray->GetElementQuantifyData())					{						mapEleData[eledata->GetName().GetBuffer()].push_back(EleAreaPercentage(other->GetActualArea() / allPartArea, eledata));					}				}							}			// third,we calculate all the element's new percentage data and get a new element chemistry list.			CElementChemistriesList newCheList;			for (auto eledata : mapEleData)			{				CElementChemistryPtr newEleche = CElementChemistryPtr(new CElementChemistry());				newEleche->SetName(CString(eledata.first.c_str()));				double newPercentage = 0;				for (auto d : eledata.second)				{					newPercentage += d.areaPercentage * d.eleData->GetPercentage();				}				newEleche->SetPercentage(newPercentage);				newCheList.push_back(newEleche);			}			CPosXrayPtr xray(new CPosXray());			xray->SetElementQuantifyData(newCheList);			newPart->SetXrayInfo(xray);			newPart->SetSubParticles(partsStr);			newPart->SetActualArea(allPartArea);			partTagId++;			newPart->SetTagId(partTagId);			newPart->SetAnalysisId(partTagId);			std::string name = p->TypeName();			newPart->TypeName(name);			newPart->TypeColor(p->TypeColor());			mergedParts.push_back(newPart);		}		return true;	}				}
 |