posted on: 2009-01-30 07:44:06
How I am making a QImage from a numpy array

>My first attempt at do this was to Create a new QImage and then set all of the pixels. This was slow. For a small image we were looking at 10 seconds! Don't do that, I recieved some advice from PyQwt mailing list. There is supposed to be a conversion function...which doesn't work at the moment, so they have a work around using the QImage constructor, but for my case the new method is amazing compared to pixel by pixel (did I mention don't do that?).

result = QtGui.QImage(bgra.data, w, h, QtGui.QImage.Format_RGB32)
result.ndarray = bgra

Where bgra is a numpy array of unsigned integers with shape, (h,w,4) and the 4 index referes to the colors. Using the result.ndarray=bgra, I suspect, creates a persistent reference to the data as per: QImage.

You could also use this technique to create other formats, and if you wanted to create a grayscale image.

h,w = x.shape
COLORTABLE = [~((i + (i<<8) + (i<<16))) for i in range(255,-1,-1)]

image = QtGui.QImage(x.data,w,h,QtGui.QImage.Format_Indexed8)
image.setColorTable(COLORTABLE)
image.ndarray = x

Be carefull with this constructor because: "data must be 32-bit aligned"QImage Contstructor, This means that if your width is not divisible by four your image will wrap funny. Here is an example of converting a numpy array to a gray scale image, with the problem.

numpy_qimage_test.py

Eventually I will post my image processing code.

Comments

Omer
2015-12-21 14:25:16
Wow!!! Looking for something like this forever! It also works if you use cv2.cvtColor from BGR to RGB and then use FORMAT_RGB888, but cv2.cvtColor works really slow (for me). I implemented my own BGR to RGB but that didn't work for me.. odd :/
Name: