In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to use Python to do a screen recording tool, I believe that many inexperienced people do not know what to do, so this article summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.
First, write in front
As a test, sometimes we often encounter the need to record their own operations by screenshot, so as to facilitate the positioning of follow-up developers. In the past, we used to use ScreenToGif to screenshot and make dynamic maps, and occasionally we can see that python can also be realized. Then hurry up and study.
Second, effect display
Third, knowledge string
There may be more things to talk about this time, involving the production of pyqt5 GUI software, the use of QThread multithreading, the graphic operation of Sikuli library, the simulated keyboard operation of win32 library, the writing of video files of cv2 library, and so on. Let's nibble away at the code I wrote this time.
1. GUI interface making.
This time I am using the ready-made Pyqt5 interface layout class, QVBoxLayout. This class can quickly help me to complete the vertical distribution of buttons, and buttons are more convenient to add.
Button1 = QPushButton ("Custom screencap") layout.addWidget (button1)
The button is named and added in two lines of code. When I used to play qt, I used qt's UI interface, and the corresponding component code was more complex. Therefore, you can use the QVBoxLayout class when developing a small number of buttons and simple layouts. If you prefer a horizontal layout, you can use the QHBoxLayout class, using the same method.
In addition, when the button clicks the associated function, that is, the work () method, if you want to take parameters, you can do so through the lambda anonymous function. It's a little trick, too.
# without parameter button1.clicked.connect (self.work) # with parameter button1.clicked.connect (lambda: self.work (1))
2. Multithreaded use of QThread class
Because the screencap tool has two functions: start and stop, I started with a single thread and found that the tool would get stuck. After looking up some data, it is found that multithreading should be used for this situation, and there is a multithreading class-QThread in the QT library itself.
The usage method is achieved by inheriting the QThread class and overriding the run method.
(but in fact, QT gods do not approve of this method of use. I will briefly explain the better use of multithreading in the second article.)
Note that the work () function must be a Ui_Mainwindow class method, because if it is not a class method, it will cause the life cycle to end directly when running GUI, causing the screencap code to report an error exit before it is run.
Class WorkThread (QThread): def _ _ init__ (self, n): super (WorkThread, self). _ _ init__ () self.n = n def run (self): XXXXX
3. Pattern recognition in sikuli library.
Because of the usage and introduction of this library, I have already mentioned it in my previous blog. So simply render the code. The main purpose of this code is that when you customize screencap, you can obtain the coordinate values of the selection range and pass the values to the recording function to complete the custom screencap function.
Def SelectRegion (): jvmPath = jpype.get_default_jvm_path () jpype.startJVM (jvmPath,'- ea','- Djava.class.path=F:\\ sikuli\\ 1\\ sikulixapi.jar') # load jar package path Screen = jpype.JClass ('org.sikuli.script.Screen') myscreen = Screen () region = myscreen.selectRegion () # Custom get screen range return region
4. Win32 library simulates keyboard operation.
In fact, this library can be used without it. Why should I use it? The main purpose is to make it convenient for users to automatically reduce the tool interface when screencap. Everything is for the users!
The following code is used to narrow the tool window, where 91 represents the left win key and 40 represents the direction down key. * that is, the win+ down arrow can achieve the window reduction function. * keybd_event (91,0,0,0) indicates that the win key is pressed
Keybd_event (91,0, win32con.KEYEVENTF_KEYUP, 0) releases the win key.
In addition, why add sleep (0.5) here? This is because it is necessary to delay pressing the direction key after pressing the win key, otherwise it will not work.
Def Minimize_Window (): win32api.keybd_event (91,0,0,0) time.sleep (0.5) win32api.keybd_event (40,0,0,0) time.sleep (0.5) win32api.keybd_event (91,0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event (40,0, win32con.KEYEVENTF_KEYUP, 0)
5. Master code for screencap
This code actually has a lot of similar code on the Internet, and I have added comments, I believe you should be able to understand. What I want to note here is how to stop screencap.
If you have a way to find out how to stop screencap online, many people will write the following code:
If cv2.waitKey (1) & 0xFF = = ord ('q'): break
Then I'll tell you that pressing the Q key will stop screencap. But you will find that the actual situation can not stop at all, why? Because there is also a code displayed on the screen:
Cv2.imshow ('imm', img_bgr) if cv2.waitKey (1) & 0xFF = = ord (' q'): break
If you don't do it yourself, you think everything will be all right, but you are wrong. Writing in this way will cause your computer screen to be bullied by every frame! Because of the use of while True, so every frame will be displayed, that is, 1S 25 frames will be constantly displayed on your desktop!
Therefore, to sum up the problem, I adopted a tricky method: generate a tag file at the beginning of screencap, and judge whether to stop screencap by whether the tag file is deleted or not.
Fourth, sample code
1. Tool GUI interface code:
# coding=utf-8# @ Software: PyCharm#Python learning group 827513319import sysfrom PyQt5.QtCore import * from PyQt5.QtWidgets import * import timeimport win32api,win32confrom recording import * class WorkThread (QThread): def _ _ init__ (self, n): super (WorkThread, self). _ init__ () self.n = n def run (self): if self.n = = 1: Minimize_Window () Recording (1) elif self.n = = 2: Minimize_Window () Recording (2) else: StopRecording () def Minimize_Window (): win32api.keybd_event (91) 0,0,0) time.sleep (0.5) win32api.keybd_event (40,0,0,0) time.sleep (0.5) win32api.keybd_event (91,0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event (40,0, win32con.KEYEVENTF_KEYUP, 0) class Ui_Mainwindow (): def setupUi (self Top): # Vertical layout class QVBoxLayout layout = QVBoxLayout (top) # add screencap related button button1 = QPushButton ("Custom Screenshot") layout.addWidget (button1) button2 = QPushButton ("full Screenshot") layout.addWidget (button2) button3 = QPushButton ("stop screencap") layout.addWidget (button3) self.text = QPlainTextEdit ('Welcome!') Layout.addWidget (self.text) button1.clicked.connect (lambda: self.work (1)) button2.clicked.connect (lambda: self.work (2)) button3.clicked.connect (lambda: self.work (3) def work (self, n): if n = = 1: print ('Custom screencap:') self.text.setPlainText ('screencap is in progress, please wait …') Elif n = = 2: print ('full screenshot selected:') self.text.setPlainText ('screencap is in progress, please wait …') Else: print ('selected to end screencap:') self.text.setPlainText ('screencap is over! (click the close button to exit the program!) Self.workThread = WorkThread (n) self.workThread.start () if _ _ name__ = "_ _ main__": app = QApplication (sys.argv) top = QWidget () top.setWindowTitle ('screencap gadget') top.resize (300,170) ui = Ui_Mainwindow () ui.setupUi (top) top.show () sys.exit (app.exec_ ()) # coding=utf-8
2. Screencap function
# coding=utf-8# @ Software: PyCharmfrom PIL import ImageGrabimport numpy as npimport cv2import osimport jpypedef Recording (tag=1): # create test.txt at the beginning of screencap as a condition for ending screencap # Python Learning Group 827513319 if not os.path.exists ('test.txt'): F = open (' test.txt', 'w') f.close () # Custom screencap or full screencap if tag= = 1: r = SelectRegion () record_region = (r.x, r.y) R.w + r.x, r.h + r.y) # Custom screencap range (upper left coordinates, lower right coordinates) elif tag = = 2: record_region = None image = ImageGrab.grab (record_region) # get the specified screen object width, height = image.size fourcc = cv2.VideoWriter_fourcc (* 'XVID') video = cv2.VideoWriter (' test.avi', fourcc, 25, (width) Height)) # default video is 25 frames while True: captureImage = ImageGrab.grab (record_region) # capture the specified range of screen frame = cv2.cvtColor (np.array (captureImage)) Cv2.COLOR_RGB2BGR) video.write (frame) # write each frame to a video file # condition for stopping screencap: test.txt is deleted if not os.path.exists ('test.txt'): break video.release () cv2.destroyAllWindows () def SelectRegion (): jvmPath = jpype.get_default_jvm_path () jpype.startJVM (jvmPath,'-ea') '- Djava.class.path=F:\\ sikuli\\ 1\ sikulixapi.jar') # load jar package path Screen = jpype.JClass (' org.sikuli.script.Screen') myscreen = Screen () region = myscreen.selectRegion () # Custom get screen range return regiondef StopRecording (): os.remove ('test.txt') # trigger condition for stopping screencap if _ name__ = = "_ main__": Recording ()
So far, the code development of the screencap gadget has been basically realized. But if you are not familiar with the related libraries in the code, or if you have not downloaded the relevant libraries, then I am sure you will encounter a lot of holes.
After reading the above, do you know how to use Python to make a screen recording tool? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.