[IPOL discuss] RGB->gray conversion and speed comparison

Nicolas Limare nicolas.limare at cmla.ens-cachan.fr
Fri Jul 29 16:55:24 CEST 2011


> > Otherwise, I have no doubts about its portability.  There is no
> > dependency on sign representation or endianness in Nicolas' solution.
> > Bitwise operations are defined in the C standard just like the
> > arithmetic operations.
> 
> I think the problem could arise in this bit-wise AND:
> "& (1 << 14)"
> 
> Not all architectures will store the 14th bit in the same position inside
> a integer.

But (1<<14) doesn't mean "the 14th bit", it means 1 * 2^14 = 16384, as
written in K&R2 Annex A7.8 "Shift Operators", p 206:
"The value of E1<<E2 is E1 (interpreted as a bit pattern) left-shifted by
E2 bits; in the absence of overflow, this is equivalent to
multiplication by 2^E2. The value of E1>>E2 is E1 right-shifted E2 bit
positions. The right shift is equivalent to division by 2^E2 ie E1 is
unsigned or if it has a non-negative value [...]"

The meaning of >> and << is not related to the memory representation
of the numbers.
 
So "x & (1<<14)" means "16384 if 16384 appears in the binary
decomposition of x, 0 if it does not", and "(x & (1<<14)) >> 14" means
"1 when x/32768. has a fractional part >= .5, 0 if it does not".

After verifying in K&R2, it appears to me that "(x>>15) + ((x &
(1<<14)) >> 14)" always is the correctly rounded x/32768. division on
systems with an ANSI C compiler. I had the same doubts as Miguel before.

And answering to Pascal: 
> The only point to worry about is that the arithmetic requires integers
> that are at least 24 bits.

Where does this condition come from?

>  This can be ensured with the UNIX stdint.h
> uint32_t type or unsigned __int32 on Windows.

According to http://www.unix.org/version2/whatsnew/lp64_wp.html,
Windows 3.1 and Apple Macintosh had a LP32 data model, meaning that
int as 16 bits wide. Most of today's 32bit systems use the ILP32 data
model, with 32bit int.

Maybe the int type width can be tested on any system (not only Windows
or UNIX) ar run-time with
    assert (sizeof(int) >= 3);
or at compile-time with
    #if (UINT_MAX>>24 == 0)
    #error int type must have 24 bits or more for correct arithmetics
    #endif

> > we would also have a correct conversion for images
> > expressed in a non-sRGB color space.
> 
> Beware that PNG's gamma and color correction is controversial:

I was not thinking about gamma, more about a cHRM png information
defining custom values for R, G and B chromaticities.

-- 
Nicolas LIMARE - CMLA - ENS Cachan    http://www.cmla.ens-cachan.fr/~limare/
IPOL - image processing on line                          http://www.ipol.im/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: Digital signature
URL: <http://tools.ipol.im/mailman/archive/discuss/attachments/20110729/e1cb9b6f/attachment.pgp>


More information about the discuss mailing list