download filterBlobRepositioning.pas
Language: Delphi
Copyright: (C) 2004 Durand Emmanuel (C) 2004 Burgel Eric
LOC: 376
Project Info
Filters
Server: SourceForge
Type: cvs
...ilters\Filters1\Src\Delphi\
   ...ractfilterNeighbor3.pas
   Chronometer.pas
   divers.pas
   filter.pas
   filterAdjust.pas
   filterArithmeticAdd.pas
   ...ithmeticConstantAdd.pas
   ...ArithmeticSubstract.pas
   filterBlobBalance.pas
   filterBlobExplorer.pas
   filterBlobGrouping.pas
   ...erBlobRepositioning.pas
   ...rBlobRepositioning2.pas
   filterBlur.pas
   filterCanny.pas
   filterContour.pas
   filterContrastExplorer.pas
   filterConvolution.pas
   filterCoocurenceMatrix.pas
   filterCopy.pas
   filterCorrelation.pas
   filterCutter.pas
   filterDistancesMap.pas
   filterExplorer.pas
   ...nisotropicDiffusion.pas
   ...GranularityExplorer.pas
   filterHistogram.pas
   ...erHistogramContrast.pas
   filterImageCreator.pas
   filterImageLoader.pas
   filterImageSaver.pas
   filterIntegration.pas
   filterInvert.pas
   filterLocalDeviation.pas
   filterLogPolar.pas
   filterMedian.pas
   filterMorphology.pas
   ...onMaximaSuppression.pas
   filterNormalize.pas
   filterOnOffCell.pas
   filterProjectionLine.pas
   filterPyramid.pas
   filterRescaleIntensity.pas
   filterResize.pas
   filterRotation.pas
   filterSigmoid.pas
   filterSmoothBilateral.pas
   filterSobel.pas
   filterSPV.pas
   filterStackProcessor.pas
   filterStackSmasher.pas
   ...erStandardDeviation.pas
   filterSUSAN.pas
   filterThresholdBinary.pas
   filterVectorHistogram.pas
   filterWavelets.pas
   filterWaves.pas
   fmask.pas
   fparameters.pas
   image.pas
   imageIO.pas
   imageIOVideo.pas
   lacModel.pas
   polygonalyzation.pas
   wrapper_itk.pas
   wrapper_opencv.pas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
unit filterBlobRepositioning;
(* ***** BEGIN LICENSE BLOCK *****
 * Copyright (C) 2004 Durand Emmanuel
 * Copyright (C) 2004 Burgel Eric
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Contact :
 *   filters@edurand.com
 *   filters@burgel.com
 *
 * ***** END LICENSE BLOCK ***** *)

{
 edurand (filters@edurand.com)
 eburgel (filters@burgel.com)
}

interface
uses
  filter, fparameters, image, Chronometer, windows,
  filterVectorHistogram, filterBlobExplorer, filterRotation, filterCopy,
  filterResize, filterCorrelation, filterBlobBalance;

type
  TFilterBlobRepositioning = class(TFilter)
  public
    constructor Create; override;
    destructor Destroy; override;
    procedure Run(); override;
    procedure Run(command:String); override;
    procedure setParameterInteger( const aName: String;  const aValue: Int64); override;
  private
    parameterImageIn : TParameterImage;
    //parameterBlob : TParameterPointer;
    parameterBlob_ThresholdBackground : TParameterInteger;
    parameterBlobAreaMin, parameterBlobAreaMax  : TParameterInteger;
    parameterMonitoring : TParameterBoolean;
    parameterVectorhistogramSmooth : TParameterInteger ;
    parameterVectorhistogramAngleprecision : TParameterInteger ;
    parameterMargin : TParameterInteger ;
    outputparameterImageOutMonitoring : TParameterImage;
    ouputParameterAngle : TParameterSingle;
    outputparameterImageOut : TParameterImage;
    inImage, outImage : PBitmap32;
    inImageBlob : PBitmap32;
    imageOutMonitorings : ArrayOfPBitmap32;
    smooth, margin : Integer;
    blobThreshold, blobAreaMin, blobAreaMax : Integer;
    blob : PBlob;
    vectorHistogram : TParameterArraySingles;
    vectorHistogramToMatch : Array of Single;
    vectorHistogramAngleprecision : Integer;
    bestAngle : Single;
    learnedImage, imageToCompareWithLearnedImage : PBitmap32;
    filterBlobExplorer : TFilterBlobExplorer;
    filterVectorHistogram : TFilterVectorHistogram;
    filterRotation, filterRotationForAccurateSearch : TFilterRotation;
    filterCopy : TFilterCopy;
    filterCorrelation : TFilterCorrelation;
    filterBlobBalance : TFilterBlobBalance;
    chrono : TChronometer;
    procedure _run();
    procedure destroyImageOuts();
    procedure createVectorHistogram();
    procedure searchAngleByVectorHistogram();
    procedure searchAccurateAngle();
    procedure extractBlobRealImage(angle:Single);
    procedure viewVectorChain(aImage : PBitmap32);
    procedure viewVectorHistogram(aImage : PBitmap32);
    procedure setDefaultVectorHistogramToMatch;
  end;

implementation

uses
  imageIO, Math, divers, SysUtils;


constructor TFilterBlobRepositioning.Create;
begin
  inherited;
  parameterImageIn:=addParameterImage('inImage', 'input image');
  //parameterBlob:=addParameterPointer('blob','a pointer on a TBlob object provides by TFilterBlobExplorer');
  parameterBlob_ThresholdBackground:=addParameterInteger('blob_ThresholdBackground','',0,255,200);
  parameterBlobAreaMin:=addParameterInteger('blob_AreaMin','explication...',0,999999,0);
  parameterBlobAreaMax:=addParameterInteger('blob_AreaMax','explication...',0,999999,999999);
  parameterMonitoring:=addParameterBoolean('monitoring','monitoring',True);
  parameterVectorhistogramSmooth := addParameterInteger('vectorHistogram_smooth', 'smooth to apply on vector histogram', 0, 50, 40) ;
  parameterVectorhistogramAngleprecision:=addParameterInteger('vectorHistogram_anglePrecision', 'The number of different bin to class all angle (0->360 degrees). For example, set 360 to have 1 bin by degre, or set 3600 to have 10 bins by degre.', 1, 36000, 360) ;
  setParameterInteger('vectorHistogram_anglePrecision',360);
  parameterMargin := addParameterInteger('margin', 'margin to add around blob before extract it', 0, 100, 10) ;
  outputparameterImageOutMonitoring := addOutputParameterImage('outImagesMonitoring', 'outImages for Monitoring');
  ouputParameterAngle := addOutputParameterSingle('angleToRestorOrientation', 'computed angle') ;
  outputparameterImageOut := addOutputParameterImage('outImage', 'outImage');
  SetLength(imageOutMonitorings,4);
  filterBlobExplorer:=TFilterBlobExplorer.Create;
  filterVectorHistogram:=TFilterVectorHistogram.Create;
  filterRotation:=TFilterRotation.Create;
  filterCopy:=TFilterCopy.Create;
  filterRotationForAccurateSearch:=TFilterRotation.Create;
  filterCorrelation:=TFilterCorrelation.Create;
  filterBlobBalance:=TFilterBlobBalance.Create;
  learnedImage:=nil;
  imageToCompareWithLearnedImage:=nil;
  chrono:=TChronometer.Create;
  vectorHistogram:=nil;
end;

destructor TFilterBlobRepositioning.Destroy;
begin
  chrono.Free;
  image.freeImage(inImageBlob);
  image.freeImage(learnedImage);
  filterBlobExplorer.Free;
  filterBlobBalance.Free;
  filterCorrelation.Free;
  filterRotationForAccurateSearch.Free;
  filterCopy.Free;
  filterRotation.Free;
  filterVectorHistogram.Free;
  destroyImageOuts();
  inherited;
end;

procedure TFilterBlobRepositioning.destroyImageOuts();
var
  i : Integer;
begin
  for i:=Low(imageOutMonitorings) to High(imageOutMonitorings) do begin
    image.freeImage(imageOutMonitorings[i]);
  end;
  // outImage is a image provided by the filterCopy filter,
  // so we do not have to delete it
end;

procedure TFilterBlobRepositioning.setParameterInteger( const aName: String;  const aValue: Int64);
begin
  if aName='vectorHistogram_anglePrecision' then begin
    if vectorHistogramAngleprecision<> aValue then begin
      vectorHistogramAngleprecision:=aValue;
      // we set a basic vectorHistogramToMatch
      setDefaultVectorHistogramToMatch();
    end;
  end;
  inherited;
end;

procedure TFilterBlobRepositioning.setDefaultVectorHistogramToMatch;
var
  i : Integer;
begin
  setLength(vectorHistogramToMatch, 0);
  setLength(vectorHistogramToMatch, vectorHistogramAngleprecision);
  for i:= 0 to vectorHistogramAngleprecision-1 do vectorHistogramToMatch[i] := 0;
  vectorHistogramToMatch[0] := 1.2 ;
  vectorHistogramToMatch[vectorHistogramAngleprecision div 4] := 1 ;
  vectorHistogramToMatch[vectorHistogramAngleprecision div 2] := 1.1 ;
  vectorHistogramToMatch[3*(vectorHistogramAngleprecision div 4)] := 1 ;
  divers.smoothIt(vectorHistogramToMatch, 10) ;
end;

procedure TFilterBlobRepositioning.run();
begin
  inImage := parameterImageIn.Image;
  if (inImage<>nil) then begin
    _run();
  end;
end;

procedure TFilterBlobRepositioning._run();
begin
  destroyImageOuts();

  smooth := parameterVectorhistogramSmooth.Value;
  margin := parameterMargin.Value;
  blobThreshold := parameterBlob_ThresholdBackground.Value;
  blobAreaMin := parameterBlobAreaMin.Value;
  blobAreaMax := parameterBlobAreaMax.Value;
  bestAngle:=0;

  inImageBlob:=image.eraseOrCreateImageLike(inImageBlob,inImage);
  filterBlobExplorer.setParameterImage('inImage',inImage);
  filterBlobExplorer.setParameterImage('outImage',inImageBlob);
  filterBlobExplorer.setParameterInteger('intensityBackground',blobThreshold);
  filterBlobExplorer.setParameterInteger('intensityPrecision',40);
  filterBlobExplorer.setParameterString('enableBlobArea','TRUE');
  filterBlobExplorer.setParameterInteger('blobAreaMin',blobAreaMin);
  filterBlobExplorer.setParameterInteger('blobAreaMax',blobAreaMax);
  filterBlobExplorer.setParameterBoolean('contour',false);
  filterBlobExplorer.setParameterBoolean('criticalPoints',True);
  filterBlobExplorer.setParameterInteger('contourCriticalPointsAppoximationAccuracy',20);
  filterBlobExplorer.setParameterString('approximationMethod','Douglas-Peucker');
  filterBlobExplorer.setParameterBoolean('blobSurfaceInfo',True);
  filterBlobExplorer.setParameterBoolean('monitoring',false);
  filterBlobExplorer.Run;
  if(Length(filterBlobExplorer.getOutputParameterArrayPointers('blobs').Pointers)>0) then begin
    blob:=filterBlobExplorer.getOutputParameterArrayPointers('blobs').Pointers[0];
    searchAngleByVectorHistogram();
    searchAccurateAngle();
   if parameterMonitoring.Value=True then begin
    // show approximatedSegmentList
    imageOutMonitorings[0]:=image.createImageFromImage(inImage);
    image.drawLines(imageOutMonitorings[0],blob.approximatedSegmentList,clYellow32,clRed32);
    // show vector chain
    imageOutMonitorings[1]:=image.createImage(Floor(blob.perimeter)+1,360);
    viewVectorChain(imageOutMonitorings[1]);
    // show vector histogram
    imageOutMonitorings[2]:=image.createImage(vectorHistogramAngleprecision, 200);
    viewVectorHistogram(imageOutMonitorings[2]);
    //imageOutMonitorings[2]:=imageIO.createImage(0,0);
    // learned image
    if imageOutMonitorings[3]=nil then begin
      if learnedImage<>nil then begin
        imageOutMonitorings[3]:=image.createImageFromImage(learnedImage);
      end else begin
        imageOutMonitorings[3]:=image.createImage(0,0);
      end;
    end;
    // set output parameter
    setOutputParameterImages('outImagesMonitoring',imageOutMonitorings);
  end;
 end else begin
   outImage:=image.createImage(1,1);
 end;
  setOutputParameterSingle('angleToRestorOrientation', bestAngle);
  setOutputParameterImage('outImage',outImage);
end;

procedure TFilterBlobRepositioning.Run(command:String);
var
  i : Integer;
begin
  if (command='learn') then begin
    image.freeImage(learnedImage);
    Run;
    if vectorHistogram<>nil then begin
      for i:= 0 to vectorHistogramAngleprecision-1 do begin
        vectorHistogramToMatch[i]:=vectorHistogram.Singles[i];
      end;
    end;
    Run;
    learnedImage:=image.createImageFromImage(outImage);
  end else
    inherited Run(command);
end;

procedure TFilterBlobRepositioning.createVectorHistogram();
begin
  filterVectorHistogram.setParameterPointer('vectorArray',blob.vectorChain);
  filterVectorHistogram.setParameterInteger('anglePrecision', vectorHistogramAngleprecision);
  filterVectorHistogram.setParameterInteger('smooth', smooth);
  filterVectorHistogram.Run;
  vectorHistogram:=filterVectorHistogram.getOutputParameterArraySingles('vectorHistogram');
end;

procedure TFilterBlobRepositioning.searchAngleByVectorHistogram();
var
  x : integer ;
  index : integer ;
  angle  : Integer ;
  sum, maxSum : Extended ;
  factor : Single;
begin
  bestAngle:=0;
  createVectorHistogram();
  maxSum := 0;
  factor:=vectorHistogramAngleprecision / 360;
  for angle :=0 to vectorHistogramAngleprecision-1 do begin
    sum := 0;
    for x := 0 to vectorHistogramAngleprecision-1 do begin
      index := x+angle;
      if index >= vectorHistogramAngleprecision then dec(index, vectorHistogramAngleprecision);
      sum := Sum + vectorHistogram.Singles[x]*vectorHistogramToMatch[index];
    end;
    if sum > maxSum then begin
      bestAngle := -angle / factor;
      maxSum := sum;
    end;
  end;
end;

procedure TFilterBlobRepositioning.extractBlobRealImage(angle:Single);
var
  outImageRotation : PBitmap32;
  roi : TRect;
  minX, maxX, minY, maxY : Integer;
  center : TFPoint;
  i, iMax : Integer;
  bestAngleR : Single;
  deltaWdiv2, deltaHdiv2 : Integer;
  time : Single;

  procedure searchMinMaxXY(inPoint:TFPoint);
  var
    outPoint : TFPoint;
  begin
    outPoint:=divers.getRotatedPoint(inPoint,center,-bestAngleR);
    outPoint.x:=outPoint.x+deltaWdiv2;
    outPoint.y:=outPoint.y+deltaHdiv2;
    minX:=Min(minX,Floor(outPoint.x));
    maxX:=Max(maxX,Floor(outPoint.x));
    minY:=Min(minY,Floor(outPoint.y));
    maxY:=Max(maxY,Floor(outPoint.y));
    //image.DrawDisk(outImageRotation,outPoint.x,outPoint.y,2,clRed32);
  end;

begin
  chrono.Start;
  // We start the repositioning by restoring the angle of the image
  filterRotation.setParameterImage('inImage',inImage);
  filterRotation.setParameterBoolean('monitoring',false);
  filterRotation.setParameterSingle('angle', angle);
  filterRotation.setParameterInteger('interpolationMode', 2);
  filterRotation.setParameterString('missingPixelColorMode', 'BLACK');
  filterRotation.setParameterBoolean('autoAdjustSize',true);
  filterRotation.Run;
  outImageRotation:=filterRotation.getOutputParameterImage('outImage').Image;
  // Next, we extract only the rectangle containing the blob.
  // To do this, we rotate all pixel of the contour of the blob, and then
  // search the rectangle containing this rotated pixel
  // But the image after the rotation may be bigger than source image,
  // so we need to calcul this difference in this pixel rotation
  deltaWdiv2:=(outImageRotation.Width-inImage.Width) div 2;
  deltaHdiv2:=(outImageRotation.Height-inImage.Height) div 2;
  center:=fpoint(inImage.Width div 2,inImage.Height div 2);
  bestAngleR:=DegToRad(angle);
  minX:=MAXINT; maxX:=-MAXINT; minY:=MAXINT; maxY:=-MAXINT;
  iMax:=Length(blob.approximatedSegmentList)-1;
  for i:=0 to iMax do begin
    searchMinMaxXY(blob.approximatedSegmentList[i].p1);
  end;
  roi.Left:=minX-margin;
  roi.Top:=minY-margin;
  roi.Right:=maxX+margin;
  roi.Bottom:=maxY+margin;
  filterCopy.setParameterImage('inImage',outImageRotation);
  filterCopy.setRegionOfInterest(roi);
  filterCopy.Run;
  // then we have our repositioned blob
  outImage:=filterCopy.getOutputParameterImage('outImage').Image;
  chrono.Stop;
  time:=chrono.getTime();
end;

procedure TFilterBlobRepositioning.viewVectorHistogram(aImage : PBitmap32);
Var
  x, y : integer ;
Begin
  image.eraseImage(aImage);
  for x:=0 to vectorHistogramAngleprecision-1 do Begin
    y := round(vectorHistogram.Singles[x]) ;
    if y >= 200 then y := 199 ;
    image.drawLine(aImage, x, 199, x, 199-y, clRed32);
  end ;
End ;

procedure TFilterBlobRepositioning.viewVectorChain(aImage : PBitmap32);
var
  i, iMax : Integer;
  x, j : Integer;
  h2 : Array of Single;
begin
    SetLength(h2,aImage.Width);
    x:=0;
    iMax:=Length(blob.vectorChain)-1;
    for i:=0 to iMax do begin
      for j:=0 to Floor(blob.vectorChain[i].length)-1 do begin
        h2[x]:=RadToDeg(blob.vectorChain[i].angle);
        Inc(x);
      end;
    end;
    smoothIt(h2, smooth) ;
    iMax:=Length(h2)-1;
    for i:=0 to iMax do begin
      image.drawLine(aImage,i,aImage.Height-1,i,aImage.Height-1-h2[i],clRed32);
    end;
    image.drawLine(aImage,0,aImage.Height-1,aImage.Width-1,aImage.Height-1,clGray32,2);
    SetLength(h2,0);
end;

procedure TFilterBlobRepositioning.searchAccurateAngle();
var
  angleDelta, angleDeltaMin, angleDeltaMax, angleDeltaInc : Single;
  bestCorrelation, correlationForAngleDelta : Single;
  accurateAngle : Single;

  procedure calculCorrelationForAngleDelta();
  begin
      filterRotationForAccurateSearch.setParameterImage('inImage',outImage);
      filterRotationForAccurateSearch.setParameterBoolean('monitoring',false);
      filterRotationForAccurateSearch.setParameterSingle('angle', angleDelta);
      filterRotationForAccurateSearch.setParameterInteger('interpolationMode', 2);
      filterRotationForAccurateSearch.setParameterString('missingPixelColorMode', 'MIRROR');
      filterRotationForAccurateSearch.setParameterBoolean('autoAdjustSize',false);
      filterRotationForAccurateSearch.setParameterSingle('xCenter',outImage.Width div 2);
      filterRotationForAccurateSearch.setParameterSingle('yCenter',outImage.Height div 2);
      filterRotationForAccurateSearch.Run;
      imageToCompareWithLearnedImage:=filterRotationForAccurateSearch.getOutputParameterImage('outImage').Image;
      filterCorrelation.setParameterImage('inImage1',learnedImage);
      filterCorrelation.setParameterImage('inImage2',imageToCompareWithLearnedImage);
      filterCorrelation.Run;
      correlationForAngleDelta:=filterCorrelation.getOutputParameterSingle('correlation').Value;
//imageIO.copyImageToFile(imageToCompareWithLearnedImage,'c:\tmp\images\imageToCompareWithLearnedImage_'+FloatToStr(bestAngle+angleDelta)+'_'+FloatToStr(correlationForAngleDelta)+'.jpg');
  end;

begin
  if learnedImage<>nil then begin
//imageIO.copyImageToFile(learnedImage,'c:\tmp\images\learnedImage.jpg');
    // we extract the image of the blob with the current best angle
    extractBlobRealImage(bestAngle);
    // first, we search if there is an error of 180
    angleDelta:=0;
    calculCorrelationForAngleDelta;
    bestCorrelation:=correlationForAngleDelta;
    angleDelta:=180;
    calculCorrelationForAngleDelta;
    // if the correlation at 180 is better than correlation at 0
    if bestCorrelation<correlationForAngleDelta then begin
      // then we have to correct the angle of 180
      bestAngle:=bestAngle+180;
      extractBlobRealImage(bestAngle);
    end;
    // now we search the best accurate angle
    accurateAngle:=bestAngle;
    bestCorrelation:=0;
    angleDeltaInc:=0.1;
    angleDeltaMin:=-1;
    angleDeltaMax:=+1;
    angleDelta:=angleDeltaMin;
//imageIO.copyImageToFile(outImage,'c:\tmp\images\imageFoundInFirstApproximation'+FloatToStr(bestAngle)+'.jpg');
    repeat
      calculCorrelationForAngleDelta();
      // if the correlation is better, then the angle is better
      if correlationForAngleDelta>bestCorrelation then begin
        bestCorrelation:=correlationForAngleDelta;
        accurateAngle:=bestAngle+angleDelta;
      end;
      angleDelta:=angleDelta+angleDeltaInc;
    until angleDelta>angleDeltaMax;
    bestAngle:=accurateAngle;
  end;
  // extract the blob with the best found angle
  extractBlobRealImage(bestAngle);
end;

end.

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us