0

I'm trying to convert an image to this following DDS format:

| Resource Format | dwFlags  | dwRGBBitCount | dwRBitMask | dwGBitMask | dwBBitMask | dwABitMask |
+-----------------+----------+---------------+------------+------------+------------+------------+
| D3DFMT_A4R4G4B4 | DDS_RGBA | 16            | 0xf00      | 0xf0       | 0xf        | 0xf000     |

D3DFMT_A4R4G4B4 16-bit ARGB pixel format with 4 bits for each channel.

I have this python code (using Wand lib):

# source is jpeg converted to RGBA format (wand only supports RGBA not ARGB)
blob = img.make_blob(format="RGBA")

for x in range(0, img.width * img.height * 4, 4):
    r = blob[x]
    g = blob[x + 1]
    b = blob[x + 2]
    a = blob[x + 3]

    # a=255 r=91 g=144 b=72
    pixel = (a << 12 | r << 8 | g << 4 | b) & 0xffff

The first pixel I get is 64328 but I was expecting 62868.

Question:

  • Is my RGBA to ARGB conversion wrong?
  • Why am I not getting the desired result?

The expected output (left) vs the actual output (right) of my code: enter image description hereenter image description here

majidarif
  • 18,694
  • 16
  • 88
  • 133
  • 1
    The r,g,b values are in bytes (8bits) you need to scale them down to 4bit (0-16) before reassembling the pixel. – Martin Beckett May 27 '17 at 16:22
  • 1
    ps if you are doing this to work with the image, not just for a homework exercise use opencv (import cv2) it's much quicker and easier – Martin Beckett May 27 '17 at 16:23
  • @MartinBeckett thanks, finally figured it out. Although there seems to be a bit of a difference, very subtle difference in the output and the expected output. – majidarif May 27 '17 at 18:59

1 Answers1

1

With @MartinBeckett's comment about scaling down the source pixels from 8bit to 4bit. I tried to search about how to do that and finally found the solution.

Simply shift right 4 bits so 8-4=4. The final code is:

r = blob[x]     >> 4
g = blob[x + 1] >> 4
b = blob[x + 2] >> 4
a = blob[x + 3] >> 4

pixel = (a << 12 | r << 8 | g << 4 | b) & 0xffff

Although there is still a very very small difference between the output vs the expected output. (portion with difference)

Output : enter image description here
Expected : enter image description here
Source : enter image description here

majidarif
  • 18,694
  • 16
  • 88
  • 133