R
R
Reikoni2021-07-25 18:25:18
Python
Reikoni, 2021-07-25 18:25:18

How to draw with pixels in Python?

I want to draw by pixels in python, how can I implement it? In this case, you can specify the color of the pixel.
For example, I need a picture of 20x20 pixels, and I need to paint over a pixel at coordinates 3; 4 where the first is x, and the second is y and the color of this pixel is red, how to implement this? Or similar to this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2021-07-25
@fox_12

For example matplotlib:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

res = np.zeros((20, 20, 3))
res[3, 4] = [254, 0, 0]  # рисуем красный пиксель

plt.imshow(res)

60fd8bf347e84799773733.png

A
Alexander, 2021-07-26
@sanya84

In the example, the image is stretched along with the window because it is too small.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QSizePolicy, QGridLayout
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt
from PIL import Image
from PIL import ImageQt


class DrawOnPython(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Пример рисования в Python")
        self.setGeometry(300, 300, 400, 300)
        
        self.label_image = QLabel()
        self.label_image.setScaledContents(True)
        self.label_image.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.label_image.setAlignment(Qt.AlignCenter)
        
        self.layout = QGridLayout(self)
        self.layout.addWidget(self.label_image, 0, 0)
        
        self.create_image()
        self.show_image()
    def create_image(self):
        image = Image.new(mode="RGB", size=(20, 20))
        self.image = image.convert("RGBA")
        self.image.putpixel((3, 4), (255, 0, 0))
    def show_image(self):
        image_qt = ImageQt.ImageQt(self.image)
        pixmap = QPixmap.fromImage(image_qt)
        self.label_image.setPixmap(pixmap)
    
def main():
    qapp = QApplication([])
    draw_on_python = DrawOnPython()
    draw_on_python.show()
    sys.exit(qapp.exec())

if __name__ == '__main__':
    main()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question