viernes, 29 de diciembre de 2017

PyQt5: getting two pixel coordinates of an image from two mouse clicks

Me ha costado un poco resolver esto, espero que le sirva a alguien más.

A ver, la idea era mostrar una imagen en una interfaz gráfica de PyQt5 (GUI para los amigos) y seleccionar dos píxeles de la misma haciendo clic con el ratón sobre ellos. 

Encontré este código aquí:

self.image = QLabel()
self.image.setPixmap(QPixmap("C:\\myImg.jpg"))
self.image.setObjectName("image")
self.image.mousePressEvent = self.getPos

def getPos(self , event):
    x = event.pos().x()
    y = event.pos().y() 
Pero yo necesito almacenar dos clicks, no uno, porque quiero usar estos valores de las coordenadas para recortar la imagen. Estos valores, (x1, y1) y (x2, y2), los muestro en sus respectivos textEdit de la GUI.

self.image = QLabel()
self.image.setPixmap(QPixmap("C:\\myImg.jpg"))
self.image.setObjectName("image")
self.image.mousePressEvent = self.getPos

def getPos(self , event):
        self.vx.append(event.pos().x())         ## vx is a list of x coordinates
        self.vy.append(event.pos().y())         ## vy is a list of y coordinates

        if len(self.vx)<2:                      ## if we only click once, we only set (x1, y1)  
            self.x1.setText(str(self.vx[0]))    ## x1 is a textEdit where we will display the first element of the list vx
            self.y1.setText(str(self.vy[0]))    ## y1 is a textEdit where we will display the first element of the list vy
        elif len(self.vx)%2==0:                 ## if we click an even number of times, we will set both (x1, y1) and (x2, y2)
            self.x1.setText(str(self.vx[-2]))   ## We get the last two values from the lists vx and vy
            self.y1.setText(str(self.vy[-2]))
            self.x2.setText(str(self.vx[-1]))
            self.y2.setText(str(self.vy[-1]))
        else:                                   ## if we click an odd number of times, we will set (x1, y1) and leave blank (x2, y2)
            self.x1.setText(str(self.vx[-1]))
            self.y1.setText(str(self.vy[-1]))
            self.x2.setText(" ")
            self.y2.setText(" ")

Así que lo que hice fue almacenar las coordenadas en una lista, de manera que me quedo siempre con los dos últimos valores. 
¡Saludos!