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.

温泽海
  • 216
  • 3
  • 16

1 Answers1

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_()
eyllanesc
  • 235,170
  • 19
  • 170
  • 241