Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Passing pixel pointer from a Maya MImage to Qt's QImage
Simplified version of original forum post:
import ctypes
import maya.OpenMaya as om
from PySide import QtCore, QtGui
# Build a test MImage
p = "/path/to/test/image.png"
mIm = om.MImage()
# Prep MImage
# Get the width and height
wUtil = om.MScriptUtil()
wPtr = wUtil.asUintPtr()
hUtil = om.MScriptUtil()
hPtr = hUtil.asUintPtr()
mIm.getSize(wPtr, hPtr)
width = wUtil.getUint(wPtr)
height = hUtil.getUint(hPtr)
# byte size
imSize = width * height * 4
# pass pointer to QImage
buf = ctypes.c_ubyte * imSize
buf = buf.from_address(long(mIm.pixels()))
qIm = QtGui.QImage(buf, width, height, QtGui.QImage.Format_RGB32).rgbSwapped()
# Test
pix = QtGui.QPixmap.fromImage(qIm)
l = QtGui.QLabel()
Copy link

ben-hearn-sb commented Jun 22, 2016

Dude....I found your other gist that created a custom model panel with paneLayout into Qt. Almost got me there with the pointers to the pane but I was unable to resize the image correctly. After stumbling into MImage I then found this and helped me finish the job!
Thanks man, always good following your work.

  • Ben

Copy link

mottosso commented Oct 25, 2020

Re-discovered this just now when capturing the viewport into a QLabel, stellar stuff still in 2020!

import ctypes
from PySide2 import QtGui, QtWidgets, QtCore
from maya.api import OpenMaya as om, OpenMayaUI as omui

image = om.MImage()
view = omui.M3dView.active3dView()
view.readColorBuffer(image, True)

size = image.getSize()
buf = ctypes.c_ubyte * size[0] * size[1]
buf = buf.from_address(long(image.pixels()))

qimage = QtGui.QImage(
    buf, size[0], size[1], QtGui.QImage.Format_RGB32

qpixmap = QtGui.QPixmap.fromImage(qimage)

qlabel = QtWidgets.QLabel()

Copy link

justinfx commented Oct 25, 2020

@mottosso I don't even remember saving this! Guess it pays to just document everything incase someone can find it in a search result later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment