Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading and writing RGB files using OpenCV

New to python and OpenCV. I’m using OpenCV to read a jpg, I then write it to a file as hex data, I read the file back again and construct a numpy array and use imshow to show the image, but it looks different from the original image. Why did the image color get blue?

file1.py:

import cv2
import numpy as np

img = cv2.imread('D:\cat.jpg')

cv2.imshow('img', img)     #Shows the image
cv2.waitKey(3000)

with open('D:\catHex', 'wb') as f:
    f.write(img)
    f.close()

file2.py:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import cv2
import numpy as np

img = np.zeros((640,640,3), np.uint8)
row = 0
col = 0

with open('D:\catHex', 'rb') as f:

    while(row < 640):

        img[row,col,2] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,0] = ord(f.read(1))

        col = col + 1
        if(col == 640):
            col = 0
            row = row + 1

    cv2.imshow('img',img)
    cv2.waitKey(3000)

enter image description here

>Solution :

You are swapping the Red and Blue channels when reading the image in your second script, therefore, the image looks blue. The following should work as expected:

img[row,col,0] = ord(f.read(1))
img[row,col,1] = ord(f.read(1))
img[row,col,2] = ord(f.read(1))

Also you could write your while loop in the following more pythonesque way with for-loops:

for row in range(640):
    for col in range(640):
        img[row,col,0] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,2] = ord(f.read(1))

    cv2.imshow('img',img)
    cv2.waitKey(3000)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading