Advertisement
Guest User

Untitled

a guest
Jan 5th, 2023
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.08 KB | Software | 0 0
  1. Try to make a home ai with object recognition, making Javis at some point
  2.  
  3.  
  4. Just started coding like 3 days ago, I've been interested in machine learning for some time and I developed some code that might be interesting. But I don't know if the code is well written it's in python be warned.
  5.  
  6.  
  7. import sys  
  8. import os  
  9. import cv2  
  10. import numpy as np  
  11. import tensorflow as tf  
  12. from PyQt5.QtWidgets import QApplication, QFileDialog, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout  
  13. from PyQt5.QtWidgets import QTextEdit  
  14. from threading import Thread
  15.  
  16. \# Define the model architecture  
  17. model = tf.keras.Sequential()  
  18. model.add(tf.keras.layers.Conv2D(32, kernel\_size=(3, 3), activation='relu', input\_shape=(1080, 1920, 3)))  
  19. model.add(tf.keras.layers.MaxPooling2D(pool\_size=(2, 2)))  
  20. model.add(tf.keras.layers.Conv2D(64, kernel\_size=(3, 3), activation='relu'))  
  21. model.add(tf.keras.layers.MaxPooling2D(pool\_size=(2, 2)))  
  22. model.add(tf.keras.layers.Flatten())  
  23. model.add(tf.keras.layers.Dense(128, activation='relu'))  
  24. model.add(tf.keras.layers.Dense(10, activation='softmax'))  
  25. def create\_model(batch\_size):  
  26. \# Define the model architecture  
  27. model = tf.keras.Sequential()  
  28. model.add(tf.keras.layers.Dense(64, input\_shape=(batch\_size, 32)))  
  29. model.add(tf.keras.layers.Dense(64))  
  30. model.add(tf.keras.layers.Dense(10))  
  31. \# Compile the model  
  32. model.compile(optimizer=tf.keras.optimizers.Adam(),  
  33. loss=tf.keras.losses.SparseCategoricalCrossentropy(from\_logits=True),  
  34. metrics=\['accuracy'\])  
  35. return model  
  36. \# Create the model with a batch size of 160  
  37. model = create\_model(batch\_size=160)
  38.  
  39. \# Compile the model  
  40. model.compile(loss=tf.keras.losses.categorical\_crossentropy,  
  41. optimizer=tf.keras.optimizers.Adam(),  
  42. metrics=\['accuracy'\])  
  43. class AppUI(QtWidgets.QWidget):  
  44. def \_\_init\_\_(self):  
  45. super().\_\_init\_\_()  
  46. self.initUI()  
  47. def initUI(self):  
  48. \# Create a progress bar to display the predictions  
  49. self.prediction\_bar = QtWidgets.QProgressBar(self)  
  50. \# Set the style of the progress bar to match the "Ironman" aesthetic  
  51. self.prediction\_bar.setStyleSheet("""  
  52.             QProgressBar {  
  53.                 border: 2px solid #444;  
  54.                 border-radius: 5px;  
  55.                 background-color: #222;  
  56.             }  
  57.             QProgressBar::chunk {  
  58.                 background-color: #ffa500;  
  59.                 width: 10px;  
  60.             }  
  61.         """)  
  62. \# Create a label for the video file input  
  63. self.file\_label = QLabel('Video file:', self)  
  64. \# Create a line edit for entering the video file path  
  65. self.file\_edit = QLineEdit(self)  
  66. \# Create a button for selecting the video file  
  67. self.file\_button = QPushButton('Browse', self)  
  68. self.file\_button.clicked.connect(self.browseFile)  
  69. \# Create a label for the frame rate input  
  70. self.fps\_label = QLabel('Frame rate:', self)  
  71. \# Create a line edit for entering the frame rate  
  72. self.fps\_edit = QLineEdit
  73.  
  74. \# Add the progress bar to the layout  
  75.         layout = QtWidgets.QVBoxLayout(self)  
  76.         layout.addWidget(self.prediction\_bar)  
  77. def updatePrediction(self, prediction):  
  78. \# Set the value of the progress bar to the predicted value  
  79. self.prediction\_bar.setValue(prediction)  
  80. class AppUI(QWidget):  
  81. def \_\_init\_\_(self):  
  82. super().\_\_init\_\_()  
  83. self.initUI()  
  84. def initUI(self):  
  85. \# Create a label for the video file input  
  86. self.file\_label = QLabel('Video file:', self)  
  87. \# Create a line edit for entering the video file path  
  88. self.file\_edit = QLineEdit(self)  
  89. \# Create a button for selecting the video file  
  90. self.file\_button = QPushButton('Browse', self)  
  91. self.file\_button.clicked.connect(self.browseFile)  
  92. \# Create a label for the frame rate input  
  93. self.fps\_label = QLabel('Frame rate:', self)  
  94. \# Create a line edit for entering the frame rate  
  95. self.fps\_edit = QLineEdit(self)  
  96. \# Create a label for the resolution input  
  97. self.resolution\_label = QLabel('Resolution:', self)  
  98. \# Create a line edit for entering the resolution  
  99. self.resolution\_edit = QLineEdit(self)  
  100. \# Create a start button  
  101. self.start\_button = QPushButton('Start', self)  
  102. self.start\_button.clicked.connect(self.startRecognition)  
  103. \# Create a stop button  
  104. self.stop\_button = QPushButton('Stop', self)  
  105. self.stop\_button.clicked.connect(self.stopRecognition)  
  106. \# Create a text edit for displaying the predictions  
  107. self.predictions\_edit = QTextEdit(self)  
  108. \# Create a layout and add the UI elements to it  
  109.         layout = QVBoxLayout(self)  
  110.         layout.addWidget(self.file\_label)  
  111.         layout.addWidget(self.file\_edit)  
  112.         layout.addWidget(self.file\_button)  
  113.         layout.addWidget(self.fps\_label)  
  114.         layout.addWidget(self.fps\_edit)  
  115.         layout.addWidget(self.resolution\_label)  
  116.         layout.addWidget(self.resolution\_edit)  
  117.         layout.addWidget(self.start\_button)  
  118.         layout.addWidget(self.stop\_button)  
  119.         layout.addWidget(self.predictions\_edit)  
  120. def browseFile(self):  
  121. \# Open a file dialog to select the video file  
  122.         options = QFileDialog.Options()  
  123.         options |= QFileDialog.ReadOnly  
  124.         file\_name, \_ = QFileDialog.getOpenFileName(self, 'Select Video File', '',  
  125. 'Video Files (\*.mp4 \*.avi);;All Files (\*)', options=options)  
  126. \# Update the line edit with the selected file path  
  127. self.file\_edit.setText(file\_name)
  128.  
  129. def preprocess\_frames(frames):  
  130. \# Resize the frames to the desired resolution  
  131.     resized\_frames = \[\]  
  132. for frame in frames:  
  133.         resized\_frame = cv2.resize(255, (1920, 1080))  
  134.         resized\_frames.append(resized\_frame)  
  135. \# Convert the frames to tensorflow's preferred format  
  136.     processed\_frames = tf.convert\_to\_tensor(resized\_frames, dtype=tf.float32)  
  137. \# Normalize the pixel values  
  138.     normalized\_frames = processed\_frames / 255.0  
  139. return normalized\_frames
  140.  
  141. def preprocess\_input\_data(frames, fps, resolution):  
  142. \# Preprocess the frames  
  143.     preprocessed\_frames = preprocess\_frames(frames, fps, resolution)  
  144. \# Add an additional dimension for the batch size  
  145.     preprocessed\_frames = np.expand\_dims(preprocessed\_frames, axis=4)  
  146. return preprocessed\_frames  
  147. def startRecognition(self):  
  148. \# Start the recognition process in a separate thread  
  149. self.recognition\_thread = Thread(target=self.run\_recognition)  
  150. self.recognition\_thread.start()  
  151. def stopRecognition(self):  
  152. \# Stop the recognition process by interrupting the thread  
  153. self.recognition\_thread.interrupt()  
  154. def run\_recognition(self):  
  155. \# Get the video file path from the line edit  
  156.         file\_path = self.file\_edit.text()  
  157. \# Open the video file  
  158.         video = cv2.VideoCapture(file\_path)  
  159. \# Get the frame rate and resolution from the line edits  
  160.         fps = int(self.fps\_edit.text())  
  161.         width, height = map(int, self.resolution\_edit.text().split('x'))  
  162.         resolution = (width, height)  
  163. \# Read the frames from the video  
  164.         success, frame = video.read()  
  165.         frames = \[\]  
  166. while success:  
  167. \# Save the frame  
  168.             frames.append(frame)  
  169. \# Read the next frame  
  170.             success, frame = video.read()  
  171. \# Close the video file  
  172.         video.release()  
  173. \# Preprocess the input data to match the model's input shape  
  174.         input\_data = preprocess\_input\_data(frames, fps, resolution)  
  175. \# Load the tensorflow model  
  176.         model = tf.keras.models.load\_model('model.h5')  
  177. \# Generate predictions using the model  
  178.         predictions = model.predict(input\_data)  
  179. \# Display the predictions in the text edit  
  180. self.predictions\_edit.setPlainText('\\n'.join(predictions))
  181.  
  182. if \_\_name\_\_ == '\_\_main\_\_':  
  183. \# Create a Qt application  
  184.     app = QApplication(sys.argv)  
  185. \# Create an instance of the AppUI class  
  186.     ui = AppUI()  
  187. \# Show the UI  
  188.     ui.show()  
  189. \# Run the Qt application  
  190. sys.exit(app.exec\_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement