What is the problem with buttons connection in PyQt5?

2024/11/16 10:33:14

I have the problem that I cannot connect the implementation between two buttons. After I pressed the "Grayscale" button and got the grayscale image, I pressed the "Canny" button but the user interface suddenly closed. I don't know what's wrong in my code.

def getImage(self):global fnamefname = QFileDialog.getOpenFileName(self, 'Open file', 'C:\\Users\binil-ping\Desktop\CODE',"Image Files (*.jpg *.gif *.bmp *.png)")pixmap = QPixmap(fname[0])self.label.setPixmap(QPixmap(pixmap))self.resize(pixmap.width(), pixmap.height())def Grayscale(self):global edgesedges = cv2.imread(fname[0], 0)edges = cv2.GaussianBlur(edges, (5, 5), 0)height, width = edges.shape[:2]ret,edges = cv2.threshold(edges,150,255,cv2.THRESH_BINARY)kernel = np.ones((5,5),np.uint8)edges = cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel)edges = cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel)edges = QImage(edges, width, height, QImage.Format_Grayscale8)pixmap = QPixmap.fromImage(edges)self.label.setPixmap(pixmap)self.resize(pixmap.width(), pixmap.height())def Canny(self):edges2 = cv2.imread(edges[0],-1)edges2 = cv2.Canny(edges2,180,200)edges2 = QImage(edges2, width, height, QImage.Format_Grayscale8)pixmap = QPixmap.fromImage(edges2)self.label.setPixmap(pixmap)self.resize(pixmap.width(), pixmap.height())

enter image description here

Answer

There are a lot of problems with your code (including the fact that you didn't provide a minimal, reproducible example), some of them explaining the crash or possibly leading to another one (I've marked them with [*]):

  • as already pointed out, avoid using globals whenever possible (which is almost always), use class attributes instead;
  • you are continuously overwriting those globals, making everything very confusing also for debugging; in fact you're using edges for both a numpy array and a QImage;
  • [*] you are trying to cv2.imread(edges[0],-1), but not only imread expects a string, but, as a result of the previous point, at that point edges is even a QImage;
  • [*] some variables are not declared in the scope of the function (width/height in the Canny function);
  • you should really avoid using capitalized names for functions and variables, as they are usually only for class names and builtin constants;
  • there are some issues in the conversion back to QImage, I suppose that's due to the various transformations you're applying to to the array (some of them also seem unnecessary) that are not very friendly with the Format_Grayscale8 format, perhaps you should better investigate about that;

Here's a possible improvement over your code. I'm adding the widget creation parts, as it was missing in the original example.

class ShowImage(QWidget):def __init__(self):QWidget.__init__(self)layout = QVBoxLayout(self)self.label = QLabel()layout.addWidget(self.label)self.getImageBtn = QPushButton()layout.addWidget(self.getImageBtn)self.getImageBtn.clicked.connect(self.getImage)self.grayBtn = QPushButton('gray')layout.addWidget(self.grayBtn)self.grayBtn.clicked.connect(self.grayScale)self.cannyBtn = QPushButton('canny')layout.addWidget(self.cannyBtn)self.cannyBtn.clicked.connect(self.canny)self.fileName = Noneself.edges = Nonedef getImage(self):fname = QFileDialog.getOpenFileName(self, 'Open file', 'C:\\Users\binil-ping\Desktop\CODE',"Image Files (*.jpg *.gif *.bmp *.png)")if fname[0]:self.fileName = fname[0]pixmap = QPixmap(self.fileName)self.label.setPixmap(pixmap)def grayScale(self):if not self.fileName:returnedges = cv2.imread(self.fileName, 0)edges = cv2.GaussianBlur(edges, (5, 5), 0)ret,edges = cv2.threshold(edges, 150, 255, cv2.THRESH_BINARY)kernel = np.ones((5, 5), np.uint8)edges = cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel)edges = cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel)self.edges = edgesheight, width = edges.shape[:2]image = QImage(edges, width, height, QImage.Format_Grayscale8)pixmap = QPixmap.fromImage(image)self.label.setPixmap(pixmap)def canny(self):if self.edges is None:returnedges2 = cv2.Canny(self.edges, 180, 200)height, width = edges2.shape[:2]edges2 = QImage(edges2, width, height, QImage.Format_Grayscale8)pixmap = QPixmap.fromImage(edges2)self.label.setPixmap(pixmap)
https://en.xdnf.cn/q/119201.html

Related Q&A

Install ipykernel in vscode - ipynb (Jupyter)

Greetings! I am not able to install ipykernel and receiving following error. Please advise. print(Hello) Running cells with Python 3.10.5 64-bit requires ipykernel package. Run the following command to…

How do I write a form in django

I am writing a forums app for my final project in class and I am trying to write a form for creating a new thread, Basically all I need it to do is username: text box hereName of thread: Text box here…

Whats the difference between namespaces and names?

Im assuming the namespace is the allotted place in memory in which the name is to be stored. Or are they the same thing?

Finding a string in python and writing it in another file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 10 years ago.Improv…

Python error TypeError: function takes exactly 1 argument (5 given)

Traceback (most recent call last):File "wdd.py", line 164, in <module>file.write("temperature is ", temperature, "wet is ", humidity, "%\n") TypeError: fun…

Django session not available on two seperate requests

Description: In the django session docs it says:You can read it and write to request.session at any point in your view.But I cant access the session when making a second request to the same view: views…

Counting how many times there are blank lists in a list of list [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

Generating a list of random permutations of another list

So, Im trying to tackle the TSP with a Genetic Algorithm. To do that I need to create a population pool. What I want to accomplish is to create a list of random permutations that will represent a popul…

How to hide location of image in django?

models.py class UserInfo(models.Model):UID = models.CharField(max_length=50, primary_key=True, default=datetime.now().strftime("%d%y%H%S%m%M")) # default=fullname = models.CharField(max_leng…

Extracting data from multiple files with python

Im trying to extract data from a directory with 12 .txt files. Each file contains 3 columns of data (X,Y,Z) that i want to extract. I want to collect all the data in one df(InforDF), but so far i only …