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:
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)
>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)
