1 #ifndef MATRIXUTIL_HEADER_
2 #define MATRIXUTIL_HEADER_
7 /** A simple structure representing a rectangle */
9 short x0
, y0
, xend
, yend
;
11 int width() const { return xend
-x0
; }
12 int height() const { return yend
-y0
; }
13 int size() const { return width()*height(); }
15 bool contains(short x
,short y
) const
16 { return x0
<=x
&& x
<xend
&& y0
<=y
&& y
<yend
; }
19 Block(short x0_
,short y0_
,short xend_
,short yend_
)
20 : x0(x0_
), y0(y0_
), xend(xend_
), yend(yend_
) {}
25 /** A simple generic template for matrices of fixed size, uses shallow copying
26 * and manual memory management */
27 template<class T
,class I
=PtrInt
> struct MatrixSlice
{
28 typedef MatrixSlice
<const T
,I
> Const
; ///< the class is convertible to Const type
30 T
*start
; ///< pointer to the top-left pixel
31 I colSkip
; ///< how many pixels to skip to get in the next column
33 /** Initializes an empty slice */
34 MatrixSlice(): start(0) {}
36 /** Creates a shallow copy (deleting one destroys all copies) */
37 MatrixSlice(const MatrixSlice
&m
): start(m
.start
), colSkip(m
.colSkip
) {}
39 /** Converts to a matrix of constant objects (shallow copy) */
40 operator Const() const {
43 result
.colSkip
= colSkip
;
47 /** Indexing operator - returns pointer to a column */
48 T
* operator[](I column
) {
50 return start
+column
*colSkip
;
52 /** Const version of indexing operator - doesn't allow to change the elements */
53 const T
* operator[](I column
) const {
54 return constCast(*this)[column
];
57 /** Reallocates the matrix for a new size. If \p memory parameter is given,
58 * it is used for storage (the user is responsible that the matrix fits in it, etc.) */
59 void allocate( I width
, I height
, T
*memory
=0 ) {
60 ASSERT( width
>0 && height
>0 );
62 start
= memory
? memory
: new T
[width
*height
];
65 /** Releases the memory */
70 /** Returns whether the matrix is allocated (and thus usable for indexing) */
71 bool isValid() const {
75 /** Fills a submatrix of a valid matrix with a value */
76 void fillSubMatrix(const Block
&block
,T value
) {
78 // compute begin and end column starts
79 T
*begin
= start
+block
.y0
+colSkip
*block
.x0
80 , *end
= start
+block
.y0
+colSkip
*block
.xend
;
82 for (T
*it
= begin
; it
!=end
; it
+= colSkip
)
83 std::fill( it
, it
+block
.height(), value
);
85 /** Shifts the indexing of this matrix - dangerous.
86 * After calling this, only addressing or more shifts can be done (not checked).
87 * Also shifts out of the allocated matrix aren't detected */
88 MatrixSlice
& shiftMatrix(I x0
,I y0
) {
90 start
+= x0
*colSkip
+y0
;
93 /** Computes relative position of a pointer in the matrix (always 0 <= \p y < #colSkip) */
94 void getPosition(const T
*elem
,int &x
,int &y
) const {
96 PtrInt diff
= elem
-start
;
101 x
= -((-diff
-1)/colSkip
) -1;
102 y
= colSkip
- (-diff
-1)%colSkip
-1;
105 }; // MatrixSlice class template
108 /** MatrixSummer objects store partial sums of a matrix, allowing quick computation
109 * of sum of any rectangle in the matrix. It's parametrized by "type of the result",
110 * "type of the input" and "indexing type" (defaults to Int) */
111 template<class T
,class I
=PtrInt
> struct MatrixSummer
{
114 MatrixSlice
<T
,I
> sums
; ///< Internal matrix containing precomputed partial sums
117 /** Creates an empty summer */
119 /** Only empty objects are allowed to be copied (assertion) */
120 MatrixSummer( const MatrixSummer
&other
)
121 { ASSERT( !other
.isValid() ); }
122 /** Only empty objects are allowed to be assigned (assertion) */
123 MatrixSummer
& operator=( const MatrixSummer
&other
)
124 { ASSERT( !other
.isValid() && !isValid() ); return *this; }
127 /** Returns whether the object is filled with data */
128 bool isValid() const { return sums
.isValid(); }
129 /** Clears the object */
130 void free() { sums
.free(); };
132 /** Computes the sum of a rectangle (in constant time) */
133 Result
getSum(I x0
,I y0
,I xend
,I yend
) const {
134 ASSERT( sums
.isValid() );
135 return sums
[xend
][yend
] -sums
[x0
][yend
] -sums
[xend
][y0
] +sums
[x0
][y0
];
137 /** A shortcut to get the sum of a block */
138 Result
getSum(const Block
&b
) const
139 { return getSum( b
.x0
, b
.y0
, b
.xend
, b
.yend
); }
141 /** Prepares object to make sums for a matrix. If the summer has already been
142 * used before, the method assumes it was for a matrix of the same size */
143 template<class Input
> void fill(Input inp
,I width
,I height
) {
144 if ( !sums
.isValid() )
145 sums
.allocate(width
+1,height
+1);
147 // fill the edges with zeroes
148 for (I i
=0; i
<=width
; ++i
)
150 for (I j
=1; j
<=height
; ++j
)
152 // acummulate in the y-growing direction
153 for (I i
=1; i
<=width
; ++i
)
154 for (I j
=1; j
<=height
; ++j
)
155 sums
[i
][j
]= sums
[i
][j
-1] + Result(inp
[i
-1][j
-1]);
156 // acummulate in the x-growing direction
157 for (I i
=2; i
<=width
; ++i
)
158 for (I j
=1; j
<=height
; ++j
)
159 sums
[i
][j
]+= sums
[i
-1][j
];
161 }; // MatrixSummer class template
163 /** Helper structure for computing with value and squared sums at once */
164 template<class Num
> struct DoubleNum
{
168 { DEBUG_ONLY( value
= square
= std::numeric_limits
<Num
>::quiet_NaN(); ) }
171 : value(val
), square(sqr(val
)) {}
173 DoubleNum(const DoubleNum
&other
)
174 : value(other
.value
), square(other
.square
) {}
176 void unpack(Num
&val
,Num
&sq
) const { val
= value
; sq
= square
; }
178 DoubleNum
& operator+=(const DoubleNum
&other
) {
180 square
+= other
.square
;
183 DoubleNum
& operator-=(const DoubleNum
&other
) {
185 square
-= other
.square
;
188 friend DoubleNum
operator+(const DoubleNum
&a
,const DoubleNum
&b
)
189 { return DoubleNum(a
)+= b
; }
190 friend DoubleNum
operator-(const DoubleNum
&a
,const DoubleNum
&b
)
191 { return DoubleNum(a
)-= b
; }
192 }; // DoubleNum template struct
195 /** Structure for a block of pixels - also contains summers and dimensions */
196 template< class SumT
, class PixT
, class I
=PtrInt
>
197 struct SummedMatrix
{
198 typedef DoubleNum
<SumT
> BSumRes
;
199 typedef MatrixSummer
<BSumRes
> BSummer
;
201 I width
/// The width of #pixels
202 , height
; ///< The height of #pixels
203 MatrixSlice
<PixT
> pixels
; ///< The matrix of pixels
204 BSummer summer
; ///< Summer for values and squares of #pixels
205 bool sumsValid
; ///< Indicates whether the summer values are valid
207 /** Sets the size of #pixels, optionally allocates memory */
208 void setSize( I width_
, I height_
) {
212 pixels
.allocate(width
,height
);
214 /** Frees the memory */
215 void free(bool freePixels
=true) {
224 /** Just validates both summers (if needed) */
225 void summers_makeValid() const {
226 ASSERT(pixels
.isValid());
228 constCast(summer
).fill(pixels
,width
,height
);
229 constCast(sumsValid
)= true;
232 /** Justs invalidates both summers (to be called after changes in the pixel-matrix) */
233 void summers_invalidate()
234 { sumsValid
= false; }
235 /** A shortcut for getting sums of a block */
236 BSumRes
getSums(const Block
&block
) const
237 { return getSums( block
.x0
, block
.y0
, block
.xend
, block
.yend
); }
238 /** Gets both sums of a nonempty rectangle in #pixels, the summer isn't validated */
239 BSumRes
getSums( I x0
, I y0
, I xend
, I yend
) const {
240 ASSERT( sumsValid
&& x0
>=0 && y0
>=0 && xend
>x0
&& yend
>y0
241 && xend
<=width
&& yend
<=height
);
242 return summer
.getSum(x0
,y0
,xend
,yend
);
244 }; // SummedPixels template struct
248 /** Contains various iterators for matrices (see Matrix)
249 * to be used in walkOperate() and walkOperateCheckRotate() */
250 namespace MatrixWalkers
{
252 /** Iterates two matrix iterators and performs an action.
253 * The loop is controled by the first iterator (\p checked)
254 * and on every corresponding pair (a,b) \p oper(a,b) is invoked. Returns \p oper. */
255 template < class Check
, class Unchecked
, class Operator
>
256 Operator
walkOperate( Check checked
, Unchecked unchecked
, Operator oper
) {
257 // outer cycle start - to be always run at least once
258 ASSERT( checked
.outerCond() );
260 // inner initialization
262 unchecked
.innerInit();
263 // inner cycle start - to be always run at least once
264 ASSERT( checked
.innerCond() );
266 // perform the operation and do the inner step for both iterators
267 oper( checked
.get(), unchecked
.get() );
269 unchecked
.innerStep();
270 } while ( checked
.innerCond() );
272 // signal the end of inner cycle to the operator and do the outer step for both iterators
275 unchecked
.outerStep();
277 } while ( checked
.outerCond() );
283 /** Base structure for walkers */
284 template<class T
,class I
> struct RotBase
{
286 typedef MatrixSlice
<T
,I
> TMatrix
;
288 TMatrix current
; ///< matrix starting on the current element
289 T
*lastStart
; ///< the place of the last enter of the inner loop
292 RotBase( TMatrix matrix
, int x0
, int y0
)
293 : current( matrix
.shiftMatrix(x0
,y0
) ), lastStart(current
.start
) {
294 DEBUG_ONLY( current
.start
= 0; )
295 ASSERT( matrix
.isValid() );
298 void innerInit() { current
.start
= lastStart
; }
299 T
& get() { return *current
.start
; }
300 }; // RotBase class template
302 #define ROTBASE_INHERIT \
303 typedef typename RotBase<T,I>::TMatrix TMatrix; \
304 using RotBase<T,I>::current; \
305 using RotBase<T,I>::lastStart;
307 /** No rotation: x->, y-> */
308 template<class T
,class I
> struct Rotation_0
: public RotBase
<T
,I
> { ROTBASE_INHERIT
309 Rotation_0( TMatrix matrix
, const Block
&block
)
310 : RotBase
<T
,I
>( matrix
, block
.x0
, block
.y0
) {}
312 void outerStep() { lastStart
+= current
.colSkip
; }
313 void innerStep() { ++current
.start
; }
316 /** Rotated 90deg\. cw\., transposed: x<-, y-> */
317 template<class T
,class I
> struct Rotation_1_T
: public RotBase
<T
,I
> { ROTBASE_INHERIT
318 Rotation_1_T( TMatrix matrix
, const Block
&block
)
319 : RotBase
<T
,I
>( matrix
, block
.xend
-1, block
.y0
) {}
321 void outerStep() { lastStart
-= current
.colSkip
; }
322 void innerStep() { ++current
.start
; }
325 /** Rotated 180deg\. cw\.: x<-, y<- */
326 template<class T
,class I
> struct Rotation_2
: public RotBase
<T
,I
> { ROTBASE_INHERIT
327 Rotation_2( TMatrix matrix
, const Block
&block
)
328 : RotBase
<T
,I
>( matrix
, block
.xend
-1, block
.yend
-1 ) {}
330 void outerStep() { lastStart
-= current
.colSkip
; }
331 void innerStep() { --current
.start
; }
334 /** Rotated 270deg\. cw\., transposed: x->, y<- */
335 template<class T
,class I
> struct Rotation_3_T
: public RotBase
<T
,I
> { ROTBASE_INHERIT
336 Rotation_3_T( TMatrix matrix
, const Block
&block
)
337 : RotBase
<T
,I
>( matrix
, block
.x0
, block
.yend
-1 ) {}
339 void outerStep() { lastStart
+= current
.colSkip
; }
340 void innerStep() { --current
.start
; }
343 /** No rotation, transposed: y->, x-> */
344 template<class T
,class I
> struct Rotation_0_T
: public RotBase
<T
,I
> { ROTBASE_INHERIT
345 Rotation_0_T( TMatrix matrix
, const Block
&block
)
346 : RotBase
<T
,I
>( matrix
, block
.x0
, block
.y0
) {}
348 void outerStep() { ++lastStart
; }
349 void innerStep() { current
.start
+= current
.colSkip
; }
352 /** Rotated 90deg\. cw\.: y->, x<- */
353 template<class T
,class I
> struct Rotation_1
: public RotBase
<T
,I
> { ROTBASE_INHERIT
354 Rotation_1( TMatrix matrix
, const Block
&block
)
355 : RotBase
<T
,I
>( matrix
, block
.xend
-1, block
.y0
) {}
357 void outerStep() { ++lastStart
; }
358 void innerStep() { current
.start
-= current
.colSkip
; }
361 /** Rotated 180deg\. cw\., transposed: y<-, x<- */
362 template<class T
,class I
> struct Rotation_2_T
: public RotBase
<T
,I
> { ROTBASE_INHERIT
363 Rotation_2_T( TMatrix matrix
, const Block
&block
)
364 : RotBase
<T
,I
>( matrix
, block
.xend
-1, block
.yend
-1 ) {}
366 void outerStep() { --lastStart
; }
367 void innerStep() { current
.start
-= current
.colSkip
; }
370 /** Rotated 270deg\. cw\.: y<-, x-> */
371 template<class T
,class I
> struct Rotation_3
: public RotBase
<T
,I
> { ROTBASE_INHERIT
372 Rotation_3( TMatrix matrix
, const Block
&block
)
373 : RotBase
<T
,I
>( matrix
, block
.x0
, block
.yend
-1 ) {}
375 void outerStep() { --lastStart
; }
376 void innerStep() { current
.start
+= current
.colSkip
; }
380 /** A flavour of walkOperate() choosing the right Rotation_* iterator based on \p rotation */
381 template<class Check
,class U
,class Operator
>
382 inline Operator
walkOperateCheckRotate( Check checked
, Operator oper
383 , MatrixSlice
<U
> pixels2
, const Block
&block2
, char rotation
) {
386 case 0: return walkOperate( checked
, Rotation_0
<U
,I
>(pixels2
,block2
) , oper
);
387 case 1: return walkOperate( checked
, Rotation_0_T
<U
,I
>(pixels2
,block2
) , oper
);
388 case 2: return walkOperate( checked
, Rotation_1
<U
,I
>(pixels2
,block2
) , oper
);
389 case 3: return walkOperate( checked
, Rotation_1_T
<U
,I
>(pixels2
,block2
) , oper
);
390 case 4: return walkOperate( checked
, Rotation_2
<U
,I
>(pixels2
,block2
) , oper
);
391 case 5: return walkOperate( checked
, Rotation_2_T
<U
,I
>(pixels2
,block2
) , oper
);
392 case 6: return walkOperate( checked
, Rotation_3
<U
,I
>(pixels2
,block2
) , oper
);
393 case 7: return walkOperate( checked
, Rotation_3_T
<U
,I
>(pixels2
,block2
) , oper
);
394 default: ASSERT(false); return oper
;
399 /** Performs manipulations with rotation codes 0-7 (dihedral group of order eight) */
401 /** Asserts the parameter is within 0-7 */
402 static void check(int DEBUG_ONLY(r
)) {
403 ASSERT( 0<=r
&& r
<8 );
405 /** Returns inverted rotation (the one that takes this one back to identity) */
406 static int invert(int r
) {
408 return (4-r
/2)%4 *2 +r
%2;
410 /** Computes rotation equal to projecting at first with \p r1 and the result with \p r2 */
411 static int compose(int r1
,int r2
) {
412 check(r1
); check(r2
);
415 return (r1
/2 + r2
/2) %4 *2+ ( (r1
%2)^(r2
%2) );
417 }; // Rotation struct
419 /** Checked_ iterator for a rectangle in a matrix, no rotation */
420 template<class T
,class I
=PtrInt
> struct Checked
: public Rotation_0
<T
,I
> {
421 typedef MatrixSlice
<T
,I
> TMatrix
;
422 typedef Rotation_0
<T
,I
> Base
;
424 using Base::lastStart
;
426 T
*colEnd
/// the end of the current column
427 , *colsEndStart
; ///< the start of the end column
429 /** Initializes a new iterator for a \p block of \p pixels */
430 Checked( TMatrix pixels
, const Block
&block
)
431 : Base( pixels
, block
), colEnd( pixels
.start
+pixels
.colSkip
*block
.x0
+block
.yend
)
432 , colsEndStart( pixels
.start
+pixels
.colSkip
*block
.xend
+block
.y0
) {
433 ASSERT( block
.xend
>block
.x0
&& block
.yend
>block
.y0
);
437 ASSERT(lastStart
<=colsEndStart
);
438 return lastStart
!=colsEndStart
;
441 colEnd
+= current
.colSkip
;
445 ASSERT(current
.start
<=colEnd
);
446 return current
.start
!=colEnd
;
448 }; // Checked class template
450 /** Checked_ iterator for a whole QImage; no rotation, but always transposed */
451 template<class T
,class U
> struct CheckedImage
{
455 QImage
&img
; ///< reference to the image
456 int lineIndex
/// index of the current line
457 , width
/// the width of the image
458 , height
; ///< the height of the image
459 QRgb
*line
/// pointer to the current pixel
460 , *lineEnd
; ///< pointer to the end of the line
463 /** Initializes a new iterator for an instance of QImage (Qt class) */
464 CheckedImage(QImage
&image
)
465 : img(image
), lineIndex(0), width(image
.width()), height(image
.height())
466 { DEBUG_ONLY(line
=lineEnd
=0;) }
468 bool outerCond() { return lineIndex
<height
; }
469 void outerStep() { ++lineIndex
; }
471 void innerInit() { line
= (QRgb
*)img
.scanLine(lineIndex
); lineEnd
= line
+width
; }
472 bool innerCond() { return line
!=lineEnd
; }
473 void innerStep() { ++line
; }
475 QRgb
& get() { return *line
; }
476 }; // CheckedImage class template
479 /** A convenience base type for operators to use with walkOperate() */
480 struct OperatorBase
{
484 /** An operator computing the sum of products */
485 template<class TOut
,class TIn
> struct RDSummer
: public OperatorBase
{
486 TOut totalSum
, lineSum
;
489 : totalSum(0), lineSum(0) {}
490 void operator()(const TIn
&num1
,const TIn
& num2
)
491 { lineSum
+= TOut(num1
) * TOut(num2
); }
493 { totalSum
+= lineSum
; lineSum
= 0; }
494 TOut
result() ///< returns the result
495 { ASSERT(!lineSum
); return totalSum
; }
498 /** An operator performing a= (b+::toAdd)*::toMul */
499 template<class T
> struct AddMulCopy
: public OperatorBase
{
500 const T toAdd
, toMul
;
502 AddMulCopy(T add
,T mul
)
503 : toAdd(add
), toMul(mul
) {}
505 template<class R1
,class R2
> void operator()(R1
&res
,R2 f
) const
506 { res
= (f
+toAdd
)*toMul
; }
509 /** An operator performing a= b*::toMul+::toAdd
510 * and moving the result into [::min,::max] bounds */
511 template<class T
> struct MulAddCopyChecked
: public OperatorBase
{
512 const T toMul
, toAdd
, min
, max
;
514 MulAddCopyChecked(T mul
,T add
,T minVal
,T maxVal
)
515 : toMul(mul
), toAdd(add
), min(minVal
), max(maxVal
) {}
517 template<class R1
,class R2
> void operator()(R1
&res
,R2 f
) const
518 { res
= checkBoundsFunc( min
, f
*toMul
+toAdd
, max
); }
522 #endif // MATRIXUTIL_HEADER_