sbenateau
sbenateau

Reputation: 67

convert image saved in hexadecimal in a np.array to import it in opencv

I get an image stored as an object from a camera that look like this (here reduced to make it understandable):

image = np.array([['#49312E', '#4A3327', '#493228', '#472F2A'],
                  ['#452C29', '#49312E', '#4B3427', '#49312A'],
                  ['#473026', '#472F2C', '#48302B', '#4C342B']])

is it possible to 'import' it as an 'image' in opencv? I tried to look at the documentation of cv2.imdecode but could get it to work. I could preprocess this array to get it to another format but I am not sure what could 'fit' to opencv.

Thank you for your help

Upvotes: 2

Views: 999

Answers (2)

Agyey Arya
Agyey Arya

Reputation: 240

OpenCV requires either a RGB or a BGR input, which is to say you need to give the values of Red Green Blue or Blue Green Red on a scale from 0-255 (8 bit). I have shared with you the code to convert your array to an image.

Initially, I count the number of rows to find the height in terms of pixels. Then I count the number of items in a row to find the width.

Then I create an empty array of the given dimensions using np.zeros.

I then go to each cell and convert the hex code to its RGB equivalent, using the following formula #RRGGBB, R = int(RR,16), G = int(GG, 16), B = int(BB, 16). This converts the hexadecimal string to int.

#!/usr/bin/env python3

import numpy as np
import re
import cv2

# Your image
image = np.array([['#49312E', '#4A3327', '#493228', '#472F2A'],
                  ['#452C29', '#49312E', '#4B3427', '#49312A'],
                  ['#473026', '#472F2C', '#48302B', '#4C342B']])


# Enter the image height and width
height = int(len(image[0]))
width  = int(len(image[0][0]))

# Create numpy array of BGR triplets
im = np.zeros((height,width,3), dtype=np.uint8) 

for row in range (height):
    for col in range(width):
        hex = image[row, col][1:]
        R = int(hex[0:2],16) 
        G = int(hex[2:4],16) 
        B = int(hex[4:6],16) 
        im[row,col] = (B,G,R)

# Save to disk
cv2.imwrite('result.png', im)

Upvotes: 2

FabioL
FabioL

Reputation: 999

This is a very succinct and pythonic (using NumPy) way to implement a conversion from your hexadecimal values matrix to an RGB matrix that could be read by OpenCV.

image = np.array([['#49312E', '#4A3327', '#493228', '#472F2A'],
              ['#452C29', '#49312E', '#4B3427', '#49312A'],
              ['#473026', '#472F2C', '#48302B', '#4C342B']])

def to_rgb(v):
    return np.array([np.int(v[1:3],16), np.int(v[3:5],16) , np.int(v[5:7],16)])

image_cv = np.array([to_rgb(h) for h in image.flatten()]).reshape(3, 4, 3)
cv2.imwrite('result.png', image_cv)

Upvotes: 3

Related Questions