1

I want to convert a PythonMagick Image Object to a NumPy array that can be used in OpenCV, and then I want to convert it into a PIL image object. I have searched Google but cannot find any sources explaining how to do this. Can someone show me how to convert image objects between these different modules?

Shashank Shekhar
  • 3,958
  • 2
  • 40
  • 52
adithya
  • 25
  • 1
  • 7
  • 1
    What is your question? You can't expect and answer if you don't ask a question. Also show some own efforts. [ask] – Piglet Dec 25 '16 at 12:00
  • thank you I have changed it , i just want to convert them into different formats like directly from PythonMagick Image object to Numpy array – adithya Dec 25 '16 at 12:43
  • Welcome to Stack Overflow! Because you're a new user, your question came up for review. i have edited the title and the phrasing to make it clearer what you're asking. If you disagree with the edits, you can edit your question further. – K. A. Buhr Dec 28 '16 at 21:29
  • Ya I'm totally new and my english is terrible – adithya Jan 07 '17 at 16:17

1 Answers1

0

The fastest way that I've found consist in saving and opening it:

import PythonMagic
import cv2

# pm_img is a PythonMagick.Image
pm_img.write('path/to/temporary/file.png')
np_img = cv2.imread('path/to/temporary/file.png')

I haven't found any satisfactory way to convert PythonMagick images to NumPy arrays without saving them, but there is a slow way that involves using python loops:

import PythonMagick
import numpy as np

pm_img = PythonMagick.Image('path/to/image.jpg')
h, w = pm_img.size().height(), pm_img.size().width()
np_img = np.empty((h, w, 3), np.uint16) # PythonMagick opens images with 16 bit depth
                                        # It seems to store the same byte twice (weird)

for i in range(h):
    for j in range(w):
        # OpenCV stores pixels as BGR
        np_img[i, j] = (pm_img.pixelColor(j, i).quantumBlue(),
                        pm_img.pixelColor(j, i).quantumGreen(),
                        pm_img.pixelColor(j, i).quantumRed())
np_img = np_img.astype(np.uint8)

Converting NumPy arrays to PIL images is easier:

from PIL import Image

pil_img = Image.fromarray(np_img[:, :, ::-1].astype(np.uint8))

Since PIL stores images in RGB but OpenCV stores them in BGR it's necessary to change the order of the channels ([:, :, ::-1]).

Image.fromarray() takes a NumPy array with dtype np.uint8.

David Rubio
  • 144
  • 10