A
download filterBlobRepositioning2.pas
Language: Delphi
Copyright: (C) 2004 Durand Emmanuel (C) 2004 Burgel Eric
LOC: 361
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
unit filterBlobRepositioning2;
(* ***** 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,
  filterBlobExplorer, filterRotation, filterCopy, filterCorrelation,
  filterResize, filterBlobBalance;

type
  TFilterBlobRepositioning2 = 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_ThresholdBackground : TParameterInteger;
    parameterBlobAreaMin, parameterBlobAreaMax  : TParameterInteger;
    parameterMonitoring : TParameterBoolean;
    parameterMargin : TParameterInteger ;
    parameterBackgroundColorBlack : TParameterBoolean;
    outputparameterImageOutMonitoring : TParameterImage;
    ouputParameterAngle : TParameterSingle;
    outputparameterImageOut : TParameterImage;
    inImage, _innerInImage, outImage : PBitmap32;
    outImageBlob1, outImageBlob2, outImageBlob3 : PBitmap32;
    imageOutMonitorings : ArrayOfPBitmap32;
    margin : Integer;
    blobThreshold, blobAreaMin, blobAreaMax, blobIntensityPrecision : Integer;
    blob : PBlob;
    bestAngle, learnedBestAngle : Single;
    learnedImage : PBitmap32;
    filterBlobExplorer, filterBlobExplorer2, filterBlobExplorer3 : TFilterBlobExplorer;
    filterRotation : TFilterRotation;
    filterCopy : TFilterCopy;
    filterBlobBalance : TFilterBlobBalance;
    filterCorrelation : TFilterCorrelation;
    procedure _run();
    procedure destroyImageOuts();
    procedure searchAngle();
    procedure searchAngleByMinimalRectangle(angleBegin,angleEnd,angleInc:Single);
    procedure searchAngleByBlobBalance();
    procedure extractBlobRealImage(angle:Single);
    function calculCorrelation(img1,img2:PBitmap32) : Single;
    procedure setBackgroundColorOfBlob( img : PBitmap32; filterBlob : Pointer; blob : PBlob );
  end;

implementation

uses
  imageIO, Math, divers, SysUtils;


constructor TFilterBlobRepositioning2.Create;
begin
  inherited;
  parameterImageIn := addParameterImage('inImage', 'input image');
  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);
  parameterMargin := addParameterInteger('margin', 'margin to add around blob before extract it', 0, 100, 10) ;
  parameterBackgroundColorBlack := addParameterBoolean( 'backgroundColorBlack', 'set the color of the background(the part outside the blob) to black' , False );
  outputparameterImageOutMonitoring := addOutputParameterImage('outImagesMonitoring', 'outImages for Monitoring');
  ouputParameterAngle := addOutputParameterSingle('angleToRestorOrientation', 'computed angle') ;
  outputparameterImageOut := addOutputParameterImage('outImage', 'outImage');
  SetLength(imageOutMonitorings,6);
  filterBlobExplorer := TFilterBlobExplorer.Create;
  filterBlobExplorer2 := TFilterBlobExplorer.Create;
  filterBlobExplorer3 := TFilterBlobExplorer.Create;
  filterRotation := TFilterRotation.Create;
  filterCopy := TFilterCopy.Create;
  filterBlobBalance := TFilterBlobBalance.Create;
  filterCorrelation := TFilterCorrelation.Create;
  learnedImage := nil;
  learnedBestAngle := 0;
  blobIntensityPrecision := 40;
end;

destructor TFilterBlobRepositioning2.Destroy;
begin
  image.freeImage( _innerInImage );
  image.freeImage(outImageBlob3);
  image.freeImage(outImageBlob2);
  image.freeImage(outImageBlob1);
  image.freeImage(learnedImage);
  filterCorrelation.Free;
  filterBlobExplorer3.Free;
  filterBlobExplorer2.Free;
  filterBlobExplorer.Free;
  filterBlobBalance.Free;
  filterCopy.Free;
  filterRotation.Free;
  destroyImageOuts();
  inherited;
end;

procedure TFilterBlobRepositioning2.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 TFilterBlobRepositioning2.setParameterInteger( const aName: String;  const aValue: Int64);
begin
  inherited;
end;

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

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

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

  _innerInImage := image.eraseOrCreateImageLike( _innerInImage, inImage );
  image.copyImageToImage( inImage, _innerInImage );

  // extract blob from inImage : set 'outImageBlob1'
  outImageBlob1:=image.eraseOrCreateImageLike(outImageBlob1,inImage);
  filterBlobExplorer.setParameterImage( 'inImage', _innerInImage );
  filterBlobExplorer.setParameterImage( 'outImage', outImageBlob1 );
  filterBlobExplorer.setParameterInteger( 'intensityBackground', blobThreshold );
  filterBlobExplorer.setParameterInteger( 'intensityPrecision', blobIntensityPrecision );
  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];
    // if we must set the background color of the outside of the blob
    if parameterBackgroundColorBlack.Value=True then begin
      setBackgroundColorOfBlob( _innerInImage, @filterBlobExplorer, blob );
      //filterBlobExplorer.setParameterImage('inImage',_innerInImage);
      //filterBlobExplorer.Run;
      //blob := nil;
      //if( Length(filterBlobExplorer.getOutputParameterArrayPointers('blobs').Pointers)>0 ) then begin
        //blob := filterBlobExplorer.getOutputParameterArrayPointers('blobs').Pointers[0];
      //end;
    end;
    // search Angle
    if blob<>nil then begin
      searchAngle();
      if parameterMonitoring.Value=True then begin
        // show approximatedSegmentList
        imageOutMonitorings[0]:=image.createImageFromImage( _innerInImage );
        image.drawLines(imageOutMonitorings[0],blob.approximatedSegmentList,clYellow32,clRed32);
        // show something
        imageOutMonitorings[1]:=image.createImage(0,0);
        // learned image
        if imageOutMonitorings[2]=nil then begin
          if learnedImage<>nil then begin
            imageOutMonitorings[2]:=image.createImageFromImage(learnedImage);
          end else begin
            imageOutMonitorings[2]:=image.createImage(0,0);
          end;
        end;
      end;
      // set output parameter
      setOutputParameterImages('outImagesMonitoring',imageOutMonitorings);
    end;
  end;
  if outImage=nil then begin
    outImage := image._onePixelImage;
  end;
  setOutputParameterSingle('angleToRestorOrientation', bestAngle);
  setOutputParameterImage('outImage',outImage);
end;

procedure TFilterBlobRepositioning2.Run(command:String);
begin
  if (command='learn') then begin
    image.freeImage(learnedImage);
    learnedBestAngle:=0;
    Run;
    learnedImage:=image.createImageFromImage(outImage);
    learnedBestAngle:=bestAngle;
  end else
    inherited Run(command);
end;

procedure TFilterBlobRepositioning2.searchAngle();
var
  correlation1, correlation2 : Single;
begin
  bestAngle:=0;
  // search quickly with minimal rectangle method
  searchAngleByMinimalRectangle(0,360,10);
  searchAngleByMinimalRectangle(-bestAngle-10,-bestAngle+10,1);
  // if we have a learned image, we check if 180 error
  if learnedImage<>nil then begin
    extractBlobRealImage(bestAngle);
    correlation1:=calculCorrelation(learnedImage,outImage);
    extractBlobRealImage(bestAngle+180);
    correlation2:=calculCorrelation(learnedImage,outImage);
    // if the correlation at 180 is better than correlation at 0
    if correlation1<correlation2 then begin
      // then we have to correct the angle of 180
      bestAngle:=bestAngle+180;
    end;
  end;
  // now search precisely with blob balance method
  searchAngleByBlobBalance();
  searchAngleByBlobBalance();
  // we reajust with learnedBestAngle
  bestAngle:=bestAngle-learnedBestAngle;                
  // at last, extract the blob with the best found angle
  extractBlobRealImage(bestAngle);
end;

procedure TFilterBlobRepositioning2.searchAngleByMinimalRectangle(angleBegin,angleEnd,angleInc:Single);
var
  minX, maxX, minY, maxY : Single;
  center : TFPoint;
  i, iMax : Integer;
  searchAngle,searchAngleR : Single;
  width,height : Single;
  surface, minSurface : Single;

  procedure searchMinMaxXY(inPoint:TFPoint);
  var
    outPoint : TFPoint;
  begin
    outPoint:=divers.getRotatedPoint(inPoint,center,searchAngleR);
    minX:=Min(minX,outPoint.x);
    minY:=Min(minY,outPoint.y);
    maxX:=Max(maxX,outPoint.x);
    maxY:=Max(maxY,outPoint.y);
  end;

begin
  center.x:=0; center.y:=0;
  minSurface:=MaxSingle;
  searchAngle:=angleBegin;
  iMax:=Length(blob.approximatedSegmentList)-1;
  repeat
    searchAngleR:=DegToRad(searchAngle);
    minX:=MaxSingle; maxX:=-MaxSingle; minY:=MaxSingle; maxY:=-MaxSingle;
    for i:=0 to iMax do begin
      searchMinMaxXY(blob.approximatedSegmentList[i].p1);
    end;
    height:=maxY-minY;
    width:=maxX-minX;
    if width>height then begin
      surface:=height*width;
      if minSurface>surface then begin
        minSurface:=surface;
        bestAngle:=-searchAngle;
      end;
    end;
    searchAngle:=searchAngle+angleInc;
  until searchAngle>=angleEnd;
end;

procedure TFilterBlobRepositioning2.searchAngleByBlobBalance();
var
  blobs : TParameterArrayPointers;
  outBlob : PBlob;
  blobBalanceAngle : Single;
begin
  extractBlobRealImage(bestAngle); // set 'outImage'
  // extraire le blob de outImage : set 'outImageBlob'
  outImageBlob2:=image.eraseOrCreateImageLike(outImageBlob2,outImage);
  filterBlobExplorer2.setParameterImage('inImage',outImage);
  filterBlobExplorer2.setParameterImage('outImage',outImageBlob2);
  filterBlobExplorer2.setParameterInteger('intensityBackground',blobThreshold);
  filterBlobExplorer2.setParameterInteger('intensityPrecision',blobIntensityPrecision);
  filterBlobExplorer2.setParameterString('enableBlobArea','TRUE');
  filterBlobExplorer2.setParameterInteger('blobAreaMin',blobAreaMin);
  filterBlobExplorer2.setParameterInteger('blobAreaMax',blobAreaMax);
  filterBlobExplorer2.setParameterBoolean('contour',false);
  filterBlobExplorer2.setParameterBoolean('criticalPoints',True);
  filterBlobExplorer2.setParameterInteger('contourCriticalPointsAppoximationAccuracy',20);
  filterBlobExplorer2.setParameterString('approximationMethod','Douglas-Peucker');
  filterBlobExplorer2.setParameterBoolean('blobSurfaceInfo',True);
  filterBlobExplorer2.setParameterBoolean('monitoring',false);
  filterBlobExplorer2.Run;
  blobs:=filterBlobExplorer2.getOutputParameterArrayPointers('blobs');
 if Length(blobs.Pointers)>0 then begin
  outBlob:=blobs.Pointers[0];
  // monitoring
  if parameterMonitoring.Value=True then begin
    imageOutMonitorings[3]:=image.eraseOrCreateImageLike(imageOutMonitorings[3],outImageBlob2);
    image.copyImageToImage(outImageBlob2,imageOutMonitorings[3]);
  end;
  // faire un BlobBalance dessus
  filterBlobBalance.setParameterPointer('blob',outBlob);
  // monitoring
  filterBlobBalance.setParameterBoolean('monitoring',false);
  if parameterMonitoring.Value=True then begin
    filterBlobBalance.setParameterBoolean('monitoring',true);
    imageOutMonitorings[4]:=image.eraseOrCreateImageLike(imageOutMonitorings[4],outImageBlob2);
    filterBlobBalance.setParameterImage('outImageMonitoring',imageOutMonitorings[4]);
  end;
  filterBlobBalance.setParameterImage('blobImage',outImageBlob2);
  filterBlobBalance.Run;
  blobBalanceAngle:=filterBlobBalance.getOutputParameterSingle('angle').Value;
  bestAngle:=bestAngle-blobBalanceAngle;
 end;
end;

// this function is called several time
procedure TFilterBlobRepositioning2.extractBlobRealImage(angle:Single);
var
  outImageRotation : PBitmap32;
  roi : TRect;
  minX, maxX, minY, maxY : Integer;
  center : TFPoint;
  i, iMax : Integer;
  blobs : TParameterArrayPointers;
  outBlob : PBlob;

begin
  // We start the repositioning by restoring the angle of the image
  filterRotation.setParameterImage('inImage',_innerInImage);
  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 extract the blob rectangle container
  outImageBlob3:=image.eraseOrCreateImageLike(outImageBlob3,outImageRotation);
  filterBlobExplorer3.setParameterImage('inImage',outImageRotation);
  filterBlobExplorer3.setParameterImage('outImage',outImageBlob3);
  filterBlobExplorer3.setParameterInteger('intensityBackground',blobThreshold);
  filterBlobExplorer3.setParameterInteger('intensityPrecision',blobIntensityPrecision);
  filterBlobExplorer3.setParameterString('enableBlobArea','TRUE');
  filterBlobExplorer3.setParameterInteger('blobAreaMin',blobAreaMin);
  filterBlobExplorer3.setParameterInteger('blobAreaMax',blobAreaMax);
  filterBlobExplorer3.setParameterBoolean('contour',false);
  filterBlobExplorer3.setParameterBoolean('criticalPoints',False);
  filterBlobExplorer3.setParameterBoolean('blobSurfaceInfo',True);
  filterBlobExplorer3.setParameterBoolean('monitoring',false);
  filterBlobExplorer3.Run;
  // monitoring
  if parameterMonitoring.Value=True then begin
    imageOutMonitorings[5]:=image.eraseOrCreateImageLike(imageOutMonitorings[5],outImageBlob3);
    image.copyImageToImage(outImageBlob3,imageOutMonitorings[5]);
  end;
  blobs := filterBlobExplorer3.getOutputParameterArrayPointers('blobs');
  if (blobs<>nil) and (Length(blobs.Pointers)>0) then begin
    outBlob := blobs.Pointers[0];
    minX := Floor(outBlob.rectangleContainer.Left);
    maxX := Floor(outBlob.rectangleContainer.Right);
    minY := Floor(outBlob.rectangleContainer.Top);
    maxY := Floor(outBlob.rectangleContainer.Bottom);
    roi.Left:=minX-margin;
    roi.Right:=maxX+margin;
    roi.Top:=minY-margin;
    roi.Bottom:=maxY+margin;
    filterCopy.setRegionOfInterest(roi);
  end else begin
    filterCopy.unsetRegionOfInterest();
  end;
  filterCopy.setParameterImage('inImage',outImageRotation);
  filterCopy.Run;
  // then we have our repositioned blob
  outImage := filterCopy.getOutputParameterImage('outImage').Image;
end;

function TFilterBlobRepositioning2.calculCorrelation(img1,img2:PBitmap32) : Single;
begin
  filterCorrelation.setParameterImage('inImage1',img1);
  filterCorrelation.setParameterImage('inImage2',img2);
  filterCorrelation.Run;
  Result:=filterCorrelation.getOutputParameterSingle('correlation').Value;
end;

procedure TFilterBlobRepositioning2.setBackgroundColorOfBlob( img : PBitmap32; filterBlob : Pointer; blob : PBlob );
var
  i, iMax : Integer;
  imageBlobIndexBits : PColor32Array;
  dest : PColor32Array;
  blobIndex : Integer;
  backgroundColor : TColor32;
begin
  dest := img.Bits;
  imageBlobIndexBits := TFilterBlobExplorer(filterBlob^).getOutputParameterImage( 'imageBlobIndex' ).Image.Bits;
  blobIndex := blob.index;
  backgroundColor := clBlack32;
  iMax := img.Width*img.Height-1;
  for i:=0 to iMax do begin
    if( imageBlobIndexBits^[0]<>blobIndex ) then begin
      dest^[0] := backgroundColor;
    end;
    Inc( imageBlobIndexBits );
    Inc( dest );
  end;
end;



end.

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