Nawin K Sharma
Nawin K Sharma

Reputation: 1004

Reading JPG colored image and saving image into raw or binary file using Python OpenCV

I am trying to read a JPG image and want to save it in binary raw image file. Output should be in planar form, like first Red channel and so on. This code I have made till now, but it is not working. Can you suggest me what should I do?

import cv2
H = 512;
W = 512;
size = H*W;

img = cv2.imread('f.jpg')
img = cv2.resize(img, (H, W))
name = 'f'+str(H)+'x'+str(W)+'.bin'
f = open(name, 'w+b')
binary_format = bytearray(img)
f.write(binary_format)
f.close()

Upvotes: 2

Views: 2654

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207345

You can do it like this:

#!/usr/bin/env python3

import cv2
import numpy as np

# Output dimensions
H, W = 512, 512

# Open image and resize to 512x512
img = cv2.imread('image.jpg')
img = cv2.resize(img, (H, W))

# Save as planar RGB output file
name = f'f-{H}x{W}.bin'
with open(name, 'w+b') as f:
    f.write(img[...,2].copy())     # write Red channel
    f.write(img[...,1].copy())     # write Green channel
    f.write(img[...,0].copy())     # write Blue channel

I put the .copy() in there to make the data contiguous for writing. I write channel 2 first, then 1 and then 0 because OpenCV stores images in BGR order and I presume you want the red plane first.


Note that you could do the above without needing any code using ImageMagick in the Terminal:

magick input.jpg -resize 512x512 -interlace plane -depth 8 RGB:data.bin

Change the 512x512 above to 512x512\! if you are happy for the image to be distorted in aspect ratio to become the specified size.

And the reverse process of creating a JPEG from the binary, planar interleaved RGB data would be:

magick -size 512x512 -depth 8 -interlace plane RGB:data.bin reconstituted.jpg

Upvotes: 3

Related Questions