File: MyImageAnalyzer.m

package info (click to toggle)
lynkeos.app 3.1%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 15,740 kB
  • sloc: objc: 36,412; ansic: 684; cpp: 148; sh: 68; makefile: 21
file content (328 lines) | stat: -rw-r--r-- 10,008 bytes parent folder | download
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
//
//  Lynkeos
//  $Id: MyImageAnalyzer.m 585 2018-09-08 21:30:37Z j-etienne $
//
//  Created by Jean-Etienne LAMIAUD on Wed jun 6 2007.
//  Copyright (c) 2007-2013. Jean-Etienne LAMIAUD
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
#include <math.h>
#include <objc/runtime.h>

#include "processing_core.h"
#include "MyImageAnalyzerPrefs.h"
#include "MyImageAnalyzer.h"
#include "LynkeosStandardImageBufferAdditions.h"

NSString * const myImageAnalyzerRef = @"MyImageAnalyzer";
NSString * const myImageAnalyzerParametersRef = @"AnalysisParams";
NSString * const myImageAnalyzerResultRef = @"AnalysisResult";

static NSString * const K_ANALYSIS_METHOD_KEY = @"analysmethod";
static NSString * const K_ANALYZE_RECT_KEY    = @"analysrect";
static NSString * const K_QUALITY_KEY         = @"quality";
static NSString * const K_UPPER_CUTOFF_FREQ_KEY = @"upCutFreq";
static NSString * const K_LOWER_CUTOFF_FREQ_KEY = @"lowCutFreq";

void filterImageForAnalysis( LynkeosFourierBuffer *image,
                             double down,
                             double up )
{
   double vmin, vmax, bmax;
   u_short x, y, c;
   const double d2 = down*down, u2 = up*up;
   LynkeosFourierBuffer *orig;

   // Normalize the image on a [0 .. 1] range
   [image getMinLevel:&vmin maxLevel:&vmax];
   bmax = vmax - vmin;

   [image substractBias:vmin andScale:1.0/bmax];
   orig = [image copy];

   // Apply a bandpass filter
   [image directTransform];
   for( y = 0; y < image->_h; y++ )
   {
      double dy = (double)y / (double)image->_h;
      if ( dy >= 0.5 )
         dy -= 1.0;

      for ( x = 0; x < image->_halfw; x++ )
      {
         double dx = (double)x / (double)image->_w;
         const double f2 = dx*dx + dy*dy;

         if ( f2 <= d2 || f2 >= u2 )
         {
            for ( c = 0; c < image->_nPlanes; c++)
               colorComplexValue(image,x,y,c) = 0.0;
         }
      }
   }
   [image inverseTransform];

   // And multiply this gradient with the original image, in order to
   // filter out the noise from the dark parts of the image
   [image multiplyWith:orig result:image];
   [orig release];
   orig = nil;
}

@implementation MyImageAnalyzerParameters
- (id) init
{
   if ( (self = [super init]) != nil )
   {
      _analysisRect = LynkeosMakeIntegerRect(0,0,0,0);
      _method = EntropyAnalysis;
      _lowerCutoff = 0.0;
      _upperCutoff = 0.0;
   }

   return( self );
}

- (void)encodeWithCoder:(NSCoder *)encoder
{
   [encoder encodeRect:NSRectFromIntegerRect(_analysisRect)
                forKey:K_ANALYZE_RECT_KEY];
   [encoder encodeInt:_method forKey:K_ANALYSIS_METHOD_KEY];
   if ( _upperCutoff > _lowerCutoff )
   [encoder encodeDouble:_upperCutoff forKey:K_UPPER_CUTOFF_FREQ_KEY];
   [encoder encodeDouble:_lowerCutoff forKey:K_LOWER_CUTOFF_FREQ_KEY];
}

- (id)initWithCoder:(NSCoder *)decoder
{
   if ( (self = [self init]) != nil )
   {
      if ( [decoder containsValueForKey:K_ANALYZE_RECT_KEY] )
         _analysisRect = LynkeosIntegerRectFromNSRect(
                                [decoder decodeRectForKey:K_ANALYZE_RECT_KEY]);
      _method = [decoder decodeIntForKey:K_ANALYSIS_METHOD_KEY];
      if ( [decoder containsValueForKey:K_UPPER_CUTOFF_FREQ_KEY] )
         _upperCutoff = [decoder decodeDoubleForKey:K_UPPER_CUTOFF_FREQ_KEY];
      if ( [decoder containsValueForKey:K_LOWER_CUTOFF_FREQ_KEY] )
         _lowerCutoff = [decoder decodeDoubleForKey:K_LOWER_CUTOFF_FREQ_KEY];
   }

   return( self );
}
@end

@implementation MyImageAnalyzerResult
- (id) init
{
   if ( (self = [super init]) != nil )
      _quality = 0.0;

   return( self );
}

- (void)encodeWithCoder:(NSCoder *)encoder
{
   [encoder encodeDouble:_quality forKey:K_QUALITY_KEY];
}

- (id)initWithCoder:(NSCoder *)decoder
{
   if ( (self = [self init]) != nil
        && [decoder containsValueForKey:K_QUALITY_KEY] )
      _quality = [decoder decodeDoubleForKey:K_QUALITY_KEY];

   return( self );
}

- (NSNumber*) quality { return( [NSNumber numberWithDouble:_quality]  ); }
@end

/*!
 * Evaluate the power spectrum quality
 */
static double quality( LynkeosFourierBuffer *spectrum, double down, double up )
{
   u_short x, y, c;
   double q = 0.0;
   double d2 = down*down, u2 = up*up;
   u_long n = 0;

   for( c = 0; c < spectrum->_nPlanes; c++ )
   {
      double lum = (__real__ colorComplexValue(spectrum,0,0,c))
      /(double)spectrum->_w/(double)spectrum->_h;
      double planeq = 0.0;

      for( y = 0; y < spectrum->_h; y++ )
      {
         double dy = (double)y / (double)spectrum->_h;
         if ( dy >= 0.5 )
            dy -= 1.0;

         for ( x = 0; x < spectrum->_halfw; x++ )
         {
            double dx = (double)x / (double)spectrum->_w;
            const double f2 = dx*dx + dy*dy;

            if ( f2 > d2 && f2 < u2 )
            {
               LNKCOMPLEX s = colorComplexValue(spectrum,x,y,c);
               planeq += __real__ s * __real__ s + __imag__ s * __imag__ s;
               n++;
            }
         }
      }

      q += planeq / lum / lum;
   }

   return( q/(double)n );
}

static double entropy( LynkeosFourierBuffer *image, double down, double up )
{
   double v, e = 0.0;
   u_short x, y, c;
   const double area = image->_h * image->_w * image->_nPlanes;

   filterImageForAnalysis(image, down, up);

   // Compute the information, based on assumption of a normal distribution of
   // brightness transitions
   for( y = 0; y < image->_h; y++ )
   {
      for ( x = 0; x < image->_w; x++ )
      {
         for ( c = 0; c < image->_nPlanes; c++)
         {
            // Normalized brightness transition
            v = 200.0 * colorValue(image,x,y,c);
            // The probability is proportional to exp(-v*v),
            // and the information quantity is -log(p), hence v*v (200 is arbitrary)
            e += v*v;
         }
      }
   }

   e /= area;

   return( e );
}

@implementation MyImageAnalyzer
+ (ParallelOptimization_t) supportParallelization
{
   return( [[NSUserDefaults standardUserDefaults] integerForKey:
                                                      K_PREF_ANALYSIS_MULTIPROC]
           & ListThreadsOptimizations );
}

- (id <LynkeosProcessing>) initWithDocument: (id <LynkeosDocument>)document
                                 parameters:(id <NSObject>)params
{
   self = [self init];
   if ( self == nil )
      return( self );

   _document = document;
   NSAssert1( [params isMemberOfClass:[MyImageAnalyzerParameters class]],
             @"Wrong parameter class %s for Image Analyzer",
             class_getName([params class]) );
   _params = (MyImageAnalyzerParameters*)[params retain];

   _lowerCutoff = _params->_lowerCutoff;
   _upperCutoff = _params->_upperCutoff;

   // Allocate the buffer for each image
   _bufferSpectrum = [[LynkeosFourierBuffer fourierBufferWithNumberOfPlanes:1
                                        width:_params->_analysisRect.size.width
                                       height:_params->_analysisRect.size.height 
                                     withGoal: FOR_DIRECT|FOR_INVERSE] retain];
   return( self );
}

- (void) dealloc
{
   if ( _bufferSpectrum != nil )
      [_bufferSpectrum release];
   [_params release];

   [super dealloc];
}

- (void) processItem:(id <LynkeosProcessableItem>)item
{
   LynkeosIntegerRect r = _params->_analysisRect;
   id <LynkeosAlignResult> aligned =
      (id <LynkeosAlignResult>)[item getProcessingParameterWithRef:
                                                         LynkeosAlignResultRef
                                                         forProcessing:
                                                               LynkeosAlignRef];
   LynkeosIntegerSize imageSize = [item imageSize];
   MyImageAnalyzerResult *res;

   // Take alignment into account
   if ( aligned != nil )
   {
      NSAffineTransform *t
         = [[[NSAffineTransform alloc] initWithTransform:
                                                 [aligned alignTransform]]
            autorelease];
      [t invert];

      // Displace the center of the square according to the alignment
      NSPoint c = {(CGFloat)r.origin.x + (CGFloat)r.size.width/2.0,
                   (CGFloat)r.origin.y + (CGFloat)r.size.height/2.0};

      c = [t transformPoint:c];
      r.origin.x = (short)(c.x - (CGFloat)r.size.width/2.0 + 0.5);
      r.origin.y = (short)(c.y - (CGFloat)r.size.height/2.0 + 0.5);
   }

   // Convert from Cocoa to bitmap coordinates
   r.origin.y = imageSize.height - r.origin.y - r.size.height;

   // Get the sample in that image
   [item getImageSample:&_bufferSpectrum inRect:r];

   if ( _params->_method == SpectrumAnalysis )
      [_bufferSpectrum directTransform];

   // Analyze its quality
   res = [[[MyImageAnalyzerResult alloc] init] autorelease];
   switch ( _params->_method )
   {
      case SpectrumAnalysis:
         res->_quality = quality( _bufferSpectrum, _lowerCutoff, _upperCutoff );
         break;
      case EntropyAnalysis:
         res->_quality = entropy(_bufferSpectrum,  _lowerCutoff, _upperCutoff);
         break;
      default:
         NSAssert(NO, @"Invalid analysis method");
   }

   // Save the result
   [item setProcessingParameter:res withRef:myImageAnalyzerResultRef 
                  forProcessing:myImageAnalyzerRef];
}

- (void) finishProcessing
{
   // Nothing to do
}

@end