Jaden
Jaden

Reputation: 375

How to properly scale/rotate images in pyqtgraph?

I have implemented pyqtgraph inside QGraphicsView in PyQt5. When I display the image the following way, it is stretched out and expands in the same aspect ratio as the screen. How do I fix this?

image = pg.ImageItem(asarray(Image.open('pic.png')) )      
self.graphicsView.addItem(image)
image.rotate(270) 

EDIT: found out how to rotate image, so I updated question with the solution. Now I am just trying to scale it properly.

Upvotes: 3

Views: 6001

Answers (2)

iggy12345
iggy12345

Reputation: 1383

I used np.rot90() instead, it's much faster and cythonable

image = pg.ImageItem(np.rot90(np.asarray(Image.open('pic.png'))))

Upvotes: 3

Luke
Luke

Reputation: 11644

You probably want something like:

import pyqtgraph as pg
from PIL import Image
from numpy import asarray

app = pg.mkQApp()

# Set up a window with ViewBox inside
gv = pg.GraphicsView()
vb = pg.ViewBox()
gv.setCentralItem(vb)
gv.show()

# configure view for images
vb.setAspectLocked()
vb.invertY()

# display image
img_data = asarray(Image.open('/home/luke/tmp/graph.png'))
image = pg.ImageItem(img_data, axisOrder='row-major')
vb.addItem(image)

The important pieces here that set the image scaling/orientation are:

  • using ImageItem(axisOrder='row-major') because image files are stored in row-major order
  • vb.invertY() because image files have the +y axis pointing downward
  • and vb.setAspectLocked() to keep the pixels square

Upvotes: 6

Related Questions