1
+ import sys
2
+ import cv2
3
+ import numpy
4
+
5
+ from PyQt5 .QtGui import QImage , QPixmap
6
+ from PyQt5 .QtWidgets import QWidget , QApplication , QLabel , QVBoxLayout , QHBoxLayout , QPushButton , QFileDialog
7
+ from PyQt5 .QtCore import Qt
8
+
9
+
10
+ class Example (QWidget ):
11
+ def __init__ (self ):
12
+ super ().__init__ ()
13
+ self .image = None
14
+ self .label = QLabel ()
15
+ self .initUI ()
16
+
17
+ def initUI (self ):
18
+ self .label .setText ('OpenCV Image' )
19
+ self .label .setAlignment (Qt .AlignCenter )
20
+ self .label .setStyleSheet ('border: gray; border-style:solid; border-width: 1px;' )
21
+
22
+ btn_open = QPushButton ('Abir Imagen...' )
23
+ btn_open .clicked .connect (self .abrirImagen )
24
+
25
+ btn_procesar = QPushButton ('Processar Imagen' )
26
+ btn_procesar .clicked .connect (self .procesarImagen )
27
+
28
+ top_bar = QHBoxLayout ()
29
+ top_bar .addWidget (btn_open )
30
+ top_bar .addWidget (btn_procesar )
31
+
32
+ root = QVBoxLayout (self )
33
+ root .addLayout (top_bar )
34
+ root .addWidget (self .label )
35
+
36
+ self .resize (540 , 574 )
37
+ self .setWindowTitle ('OpenCV & PyQT 5 by Tutor de Programacion' )
38
+
39
+ def abrirImagen (self ):
40
+ filename , _ = QFileDialog .getOpenFileName (None , 'Buscar Imagen' , '.' , 'Image Files (*.png *.jpg *.jpeg *.bmp)' )
41
+ if filename :
42
+ with open (filename , "rb" ) as file :
43
+ data = numpy .array (bytearray (file .read ()))
44
+
45
+ self .image = cv2 .imdecode (data , cv2 .IMREAD_UNCHANGED )
46
+ # self.image = cv2.imread(filename, cv2.IMREAD_UNCHANGED)
47
+ self .mostrarImagen ()
48
+
49
+ def procesarImagen (self ):
50
+ if self .image is not None :
51
+ # self.image = cv2.GaussianBlur(self.image, (5, 5), 0)
52
+ # self.image = cv2.Canny(self.image, 100, 200)
53
+
54
+ gray = cv2 .cvtColor (self .image , cv2 .COLOR_RGB2GRAY ) \
55
+ if len (self .image .shape ) >= 3 else self .image
56
+
57
+ blur = cv2 .GaussianBlur (gray , (21 , 21 ), 0 , 0 )
58
+
59
+ self .image = cv2 .divide (gray , blur , scale = 256 )
60
+ self .mostrarImagen ()
61
+
62
+ def mostrarImagen (self ):
63
+ size = self .image .shape
64
+ step = self .image .size / size [0 ]
65
+ qformat = QImage .Format_Indexed8
66
+
67
+ if len (size ) == 3 :
68
+ if size [2 ] == 4 :
69
+ qformat = QImage .Format_RGBA8888
70
+ else :
71
+ qformat = QImage .Format_RGB888
72
+
73
+ img = QImage (self .image , size [1 ], size [0 ], step , qformat )
74
+ img = img .rgbSwapped ()
75
+
76
+ self .label .setPixmap (QPixmap .fromImage (img ))
77
+ self .resize (self .label .pixmap ().size ())
78
+
79
+ if __name__ == '__main__' :
80
+ app = QApplication (sys .argv )
81
+ win = Example ()
82
+ win .show ()
83
+ sys .exit (app .exec_ ())
0 commit comments