0

In some interface using PyQt5, let button be a QPushButton. If we want to set an icon for the button using a given saved image image.jpg, we usually write:

button.setIcon(QtGui.QIcon("image.jpg"))

However, if I am given an n-dimensional numpy array array which also represents an image, I cannot simply write button.setIcon(QtGui.QIcon(array)) as it will give an error message. What should I do to instead? (saving the array as an image is not in consideration as I want large amount of arrays to be made into PushButton)

Edit:

For a typical situation, consider:

import numpy

array = numpy.random.rand(100,100,3) * 255

Then array is a square array representing an image. To see this, we can write (we do not have to use PIL or Image to solve our problem and this is just a demonstration):

from PIL import Image
im = Image.fromarray(imarray.astype('uint8')).convert('RGBA')

Reference:100x100 image with random pixel colour

I want to make this fixed array an icon.

4
  • It depends on what shape is used for the array and the way pixels are stored. How is the array created? Are you using opencv? Commented May 8, 2022 at 20:56
  • I have updated the question. I have no problem with using opencv. Commented May 8, 2022 at 21:11
  • If you're using PIL, you should look for the ImageQt submodule. Commented May 8, 2022 at 21:16
  • We do not have to use PIL. In fact, I perfer opencv if possible. I use PIL as an example just for the purpose of demonstrating my array indeed represents an image. Commented May 8, 2022 at 21:22

1 Answer 1

1

You have to build a QImage -> QPixmap -> QIcon:

import numpy as np

from PyQt5.QtGui import QIcon, QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QPushButton

app = QApplication([])

array = (np.random.rand(1000, 1000, 3) * 255).astype("uint8")

height, width, _ = array.shape
image = QImage(bytearray(array), width, height, QImage.Format.Format_RGB888)
# image.convertTo(QImage.Format.Format_RGB32)

button = QPushButton()
button.setIconSize(image.size())
button.setIcon(QIcon(QPixmap(image)))
button.show()

app.exec_()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.