class CamShow(QMainWindow, Ui_CamShow): def __init__(self, parent=None): super(CamShow, self).__init__(parent) self.setupUi(self) self.PrepWidgets() self.PrepParameters() self.Timer = QTimer(self) self.CallBackFunctions() #self.Timer.timeout.connect(self.TimerOutFun) self.stopbt = 0 #self.draw.plotItem.showGrid(True, True, 0.7) #控件初始化 def PrepWidgets(self): self.PrepCamera() self.StopBt.setEnabled(False) self.RecordBt.setEnabled(False) self.Exposure.setEnabled(False) def PrepCamera(self): self.camera = cv2.VideoCapture(0) #self.camera.set(cv2.CAP_PROP_FRAME_WIDTH,640) #self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT,480) #self.camera.set(cv2.CAP_PROP_AUTO_EXPOSURE,0.25) #self.camera.set(cv2.CAP_PROP_EXPOSURE,float(0.1)) #self.camera.set(cv2.CAP_PROP_ISO_SPEED,100) def PrepParameters(self): self.RecordFlag = 0 # 0=not save video, 1=save self.RecordPath = 'D:/Python/PyQt/' self.FilePathLE.setText(self.RecordPath) self.Image_num = 0 self.Exposure.currentIndexChanged.connect(lambda: self.camera.get(15)) self.SetExposure() def CallBackFunctions(self): self.FilePathBt.clicked.connect(self.SetFilePath) self.ShowBt.clicked.connect(self.StartCamera) self.StopBt.clicked.connect(self.StopCamera) self.RecordBt.clicked.connect(self.RecordCamera) self.ExitBt.clicked.connect(self.ExitApp) self.Timer.timeout.connect(self.TimerOutFun) self.BtnGo.clicked.connect(self.calculate) self.Exposure.activated.connect(self.SetExposure) def SetExposure(self): exposure_time = float(self.Exposure.currentText()) print(exposure_time) self.camera.set(15, exposure_time) def StartCamera(self): self.ShowBt.setEnabled(False) self.StopBt.setEnabled(True) self.RecordBt.setEnabled(True) self.Exposure.setEnabled(True) self.GrayCheck.setEnabled(True) self.RecordBt.setText('Record') self.Timer.start(1) def StopCamera(self): if self.StopBt.text() == 'Stop': self.StopBt.setText('Continue') #self.stopbt = 0 self.RecordBt.setText('Save Pic') self.Timer.stop() else: self.StopBt.setText('Stop') #self.stopbt = 1 self.RecordBt.setText('Record') self.Timer.start(1) def TimerOutFun(self): success, self.img = self.camera.read() if self.GrayCheck.isChecked(): self.GrayImg = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) # print(self.Timer.time()) if success: self.DispImg() self.CopyImg() self.drawAvg() # print(np.sum(self.img)) # print(self.img) #self.Image_num+=1 #inputImg = cv2.imread(self.img) if self.RecordFlag: if self.GrayCheck.isChecked(): color = cv2.cvtColor( self.GrayImg, cv2.COLOR_GRAY2RGB) #再轉換一次灰階到彩色才會有三通到,儲存影片才能成功 self.video_writer.write(color) else: self.video_writer.write(self.img) def DispImg(self): if self.GrayCheck.isChecked(): qimg = qimage2ndarray.array2qimage(self.GrayImg) #CVimg = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) else: CVimg = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB) #print(CVimg.shape) qimg = qimage2ndarray.array2qimage(CVimg) self.DispLb.setPixmap(QPixmap(qimg)) self.DispLb.show() def CopyImg(self): ret = QRect(20, 200, 481, 20) if self.GrayCheck.isChecked(): qimg = qimage2ndarray.array2qimage(self.GrayImg) #CVimg = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) else: CVimg = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB) qimg = qimage2ndarray.array2qimage(CVimg) b = qimg.copy(ret) self.DispCopyImg.setPixmap(QPixmap(b)) self.DispCopyImg.show() def SetFilePath(self): dirname = QFileDialog.getExistingDirectory(self, "瀏覽", '.') if dirname: self.FilePathLE.setText(dirname) self.RecordPath = dirname + '/' def RecordCamera(self): tag = self.RecordBt.text() if tag == 'Save Pic': image_name = self.RecordPath + 'self.image' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.jpg' print(image_name) if self.GrayCheck.isChecked(): cv2.imwrite(image_name, self.CVimg) else: cv2.imwrite(image_name, self.img) elif tag == 'Record': self.RecordBt.setText('Stop') video_name = self.RecordPath + 'video' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.avi' if self.GrayCheck.isChecked(): size = (self.GrayImg.shape[1], self.GrayImg.shape[0]) else: size = (self.img.shape[1], self.img.shape[0]) fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') self.video_writer = cv2.VideoWriter(video_name, fourcc, self.camera.get(5), size) self.RecordFlag = 1 self.StopBt.setEnabled(False) self.ExitBt.setEnabled(False) elif tag == 'Stop': self.RecordBt.setText('Record') self.video_writer.release() self.RecordFlag = 0 self.StopBt.setEnabled(True) self.ExitBt.setEnabled(True) def drawAvg(self): self.draw_2.clear() #inputImg= cv2.imread(self.img) #img = cv2.imread('rgb.png') img2RGB = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(img2RGB, cv2.COLOR_RGB2GRAY) #print(img2RGB.shape) #初始化numpy arr r_arr = np.zeros((640, 1), np.uint8) g_arr = np.zeros((640, 1), np.uint8) b_arr = np.zeros((640, 1), np.uint8) Gray_arr = np.zeros((640, 1), np.uint8) for i in range(640): #print(np.sum(self.img[10:20 , i , 0] )) r_arr[i, 0] = np.sum(img2RGB[220:240, i, 0]) / 20 g_arr[i, 0] = np.sum(img2RGB[220:240, i, 1]) / 20 b_arr[i, 0] = np.sum(img2RGB[220:240, i, 2]) / 20 Gray_arr[i, 0] = np.sum(gray[220:240, i]) / 20 #rint(r_arr[0,0]) x = np.linspace(0, 640, 640) self.draw_2.setRange(xRange=[0, 640]) # 固定x軸 不會拉動 self.draw_2.setRange(yRange=[0, 255]) # 固定y軸 不會拉動 self.draw_2.plot(x, r_arr[:, 0], pen='r') self.draw_2.plot(x, g_arr[:, 0], pen='g') self.draw_2.plot(x, b_arr[:, 0], pen='b') self.draw_2.plot(x, Gray_arr[:, 0], pen='w') def calculate(self): pixel_array = [] wave_array = [] if self.P1.text(): a1 = float(self.P1.text()) pixel_array.append(a1) print("a1=", a1) if self.W1.text(): b1 = float(self.W1.text()) wave_array.append(b1) print("b1=", b1) if self.P2.text(): a2 = float(self.P2.text()) pixel_array.append(a2) if self.W2.text(): b2 = float(self.W2.text()) wave_array.append(b2) if self.P3.text(): a3 = float(self.P3.text()) pixel_array.append(a3) if self.W3.text(): b3 = float(self.W3.text()) wave_array.append(b3) if self.P4.text(): a4 = float(self.P4.text()) pixel_array.append(a4) if self.W4.text(): b4 = float(self.W4.text()) wave_array.append(b4) if self.P5.text(): a5 = float(self.P5.text()) pixel_array.append(a5) if self.W5.text(): b5 = float(self.W5.text()) wave_array.append(b5) print(pixel_array) print(wave_array) """ a1 = float(self.P1.text()) a2 = float(self.P2.text()) a3 = float(self.P3.text()) a4 = float(self.P4.text()) a5 = float(self.P5.text()) """ """ b1 = float(self.W1.text()) b2 = float(self.W2.text()) b3 = float(self.W3.text()) b4 = float(self.W4.text()) b5 = float(self.W5.text()) """ x = pixel_array y = wave_array num = int(self.comboBox.currentText()) parameter = np.polyfit(x, y, num) #parameter = np.polyfit(x,y,1) print(parameter) line = np.poly1d(parameter) print(line) #y2 = parameter[0] * x + parameter[1] #print(y2) if num == 1: result = "a1係數:" + str(parameter[0]) + "\n" + "a0係數:" + str( parameter[1]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.plot(x, y, color='g') if num == 2: result = "a2係數:" + str(parameter[0]) + "\n" + "a1係數:" + str( parameter[1]) + "\n" + "a0係數:" + str( parameter[2]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.plot(x, y, color='g') if num == 3: result = "a3係數:" + str(parameter[0]) + "\n" + "a2係數:" + str( parameter[1]) + "\n" + "a1係數:" + str( parameter[2]) + "\n" + "a0係數:" + str( parameter[3]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.plot(x, y, color='g') if num == 4: result = "a4係數:" + str(parameter[0]) + "\n" + "a3係數:" + str( parameter[1]) + "\n" + "a2係數:" + str( parameter[2]) + "\n" + "a1係數:" + str( parameter[3]) + "\n" + "a0係數:" + str( parameter[4]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.plot(x, y, color='g') if num == 5: result = "a5係數:" + str(parameter[0]) + "\n" + "a4係數:" + str( parameter[1]) + "\n" + "a3係數:" + str( parameter[2]) + "\n" + "a2係數:" + str( parameter[3]) + "\n" + "a1係數:" + str( parameter[4]) + "\n" + "a0係數:" + str( parameter[5]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.plot(x, y, color='g') def ExitApp(self): self.Timer.Stop() self.camera.release() QCoreApplication.quit()
class CamShow(QMainWindow, Ui_CamShow): def __init__(self, parent=None): super(CamShow, self).__init__(parent) self.setupUi(self) self.PrepWidgets() self.not_open = 0 #flag self.PrepParameters() self.Timer = QTimer(self) self.CallBackFunctions() self._num = 0 self.getSave_arr = [] # 存放n筆的SavePixel_arr self.getPixel_arr = [] # 存放n筆的Pixel_arr self.Timer.timeout.connect(self.TimerOutFun) self.stopbt = 0 #self.draw.plotItem.showGrid(True, True, 0.7) #控件初始化 def PrepWidgets(self): self.PrepCamera() self.StopBt.setEnabled(False) self.RecordBt.setEnabled(False) self.Exposure.setEnabled(False) self.Btn_Log.setEnabled(False) f = open('pixel_read.txt', 'r') f1 = open("wave_read.txt", 'r') lines = f.readlines() lines1 = f1.readlines() i = 0 for line in lines: _spl = line.split('\n') if i == 0: self.P1.setText(_spl[0]) elif i == 1: self.P2.setText(_spl[0]) elif i == 2: self.P3.setText(_spl[0]) elif i == 3: self.P4.setText(_spl[0]) elif i == 4: self.P5.setText(_spl[0]) elif i == 5: self.P6.setText(_spl[0]) elif i == 6: self.P7.setText(_spl[0]) elif i == 7: self.P8.setText(_spl[0]) i += 1 i = 0 for line in lines1: _spl = line.split('\n') if i == 0: self.W1.setText(_spl[0]) elif i == 1: self.W2.setText(_spl[0]) elif i == 2: self.W3.setText(_spl[0]) elif i == 3: self.W4.setText(_spl[0]) elif i == 4: self.W5.setText(_spl[0]) elif i == 5: self.W6.setText(_spl[0]) elif i == 6: self.W7.setText(_spl[0]) elif i == 7: self.W8.setText(_spl[0]) i += 1 f.close() f1.close() def PrepCamera(self): self.camera = cv2.VideoCapture(0) self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, 2560) self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 1920) self.camera.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25) #self.camera.set(cv2.CAP_PROP_EXPOSURE,float(0.1)) #self.camera.set(cv2.CAP_PROP_ISO_SPEED,100) def PrepParameters(self): self.RecordFlag = 0 # 0=not save video, 1=save self.RecordPath = 'D:/Python/PyQt/' self.FilePathLE.setText(self.RecordPath) self.Image_num = 0 # 讀取圖片的次數 self.Exposure.currentIndexChanged.connect(lambda: self.camera.get(15)) self.SetExposure() def CallBackFunctions(self): self.FilePathBt.clicked.connect(self.SetFilePath) self.ShowBt.clicked.connect(self.StartCamera) self.StopBt.clicked.connect(self.StopCamera) self.RecordBt.clicked.connect(self.RecordCamera) self.ExitBt.clicked.connect(self.ExitApp) self.Timer.timeout.connect(self.TimerOutFun) self.BtnGo.clicked.connect(self.calculate) self.Exposure.activated.connect(self.SetExposure) self.Btn_Log.clicked.connect(self.saveLog) def SetExposure(self): exposure_time = float(self.Exposure.currentText()) print(exposure_time) self.camera.set(15, exposure_time) def StartCamera(self): self.ShowBt.setEnabled(False) self.StopBt.setEnabled(True) self.RecordBt.setEnabled(True) self.Exposure.setEnabled(True) self.GrayCheck.setEnabled(True) self.RecordBt.setText('Record') self.Timer.start(1) self.timelb = time.clock() def StopCamera(self): if self.StopBt.text() == 'Stop': self.StopBt.setText('Continue') #self.stopbt = 0 self.RecordBt.setText('Save Pic') self.Timer.stop() self.Btn_Log.setEnabled(True) else: self.StopBt.setText('Stop') #self.stopbt = 1 self.RecordBt.setText('Record') self.Timer.start(1) self.Btn_Log.setEnabled(False) def TimerOutFun(self): self.not_open success, self.img = self.camera.read() if self.GrayCheck.isChecked(): self.GrayImg = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) if success: self.DispImg() self.CopyImg() self.drawAvg() self.Image_num += 1 #讀取圖片的次數 if self.not_open != 0: self.drawAvg_after_calculate() if self.RecordFlag: if self.GrayCheck.isChecked(): color = cv2.cvtColor( self.GrayImg, cv2.COLOR_GRAY2RGB) #再轉換一次灰階到彩色才會有三通到,儲存影片才能成功 self.video_writer.write(color) else: self.video_writer.write(self.img) if self.Image_num % 10 == 9: # frame_rate = 10/(time.clock()-self.timelb) # self.FpsLCD.display(frame_rate) # self.timelb=time.clock() self.FpsLCD.display(self.camera.get(5)) self.WidthLCD.display(self.camera.get(3)) self.HeightLCD.display(self.camera.get(4)) def DispImg(self): self.GrayImg = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY) #图像调整为490像素,算出新宽度與舊宽度的比值r,然后用比值r乘以舊高度,得到新高度。 r = 490.0 / self.img.shape[1] dim = (490, int(self.img.shape[0] * r)) self.resized = cv2.resize(self.img, dim, interpolation=cv2.INTER_AREA) self.Gray_resized = cv2.resize(self.GrayImg, dim, interpolation=cv2.INTER_AREA) if self.GrayCheck.isChecked(): qimg = qimage2ndarray.array2qimage(self.Gray_resized) else: CVimg = cv2.cvtColor(self.resized, cv2.COLOR_BGR2RGB) qimg = qimage2ndarray.array2qimage(CVimg) self.DispLb.setPixmap(QPixmap(qimg)) self.DispLb.show() def CopyImg(self): #ret=QRect(10,260,501,20) # QRect(int x, int y, int width, int height) r = 490 / 2560 #X = int(self.roi_X.text()) X = int(self.roi_X.text()) * r #Y = int(self.roi_Y.text()) Y = int(self.roi_Y.text()) * r #W = int(self.roi_Width.text()) W = 490 - X H = int(self.roi_Height.text()) * r ret = QRect(X, Y, W, H) if self.GrayCheck.isChecked(): qimg = qimage2ndarray.array2qimage(self.Gray_resized) else: CVimg = cv2.cvtColor(self.resized, cv2.COLOR_BGR2RGB) qimg = qimage2ndarray.array2qimage(CVimg) b = qimg.copy(ret) self.DispCopyImg.setPixmap(QPixmap(b)) self.DispCopyImg.show() def SetFilePath(self): dirname = QFileDialog.getExistingDirectory(self, "瀏覽", '.') if dirname: self.FilePathLE.setText(dirname) self.RecordPath = dirname + '/' def RecordCamera(self): tag = self.RecordBt.text() if tag == 'Save Pic': image_name = self.RecordPath + 'self.image' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.jpg' print(image_name) if self.GrayCheck.isChecked(): cv2.imwrite(image_name, self.CVimg) else: cv2.imwrite(image_name, self.img) elif tag == 'Record': self.RecordBt.setText('Stop') video_name = self.RecordPath + 'video' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.avi' if self.GrayCheck.isChecked(): size = (self.GrayImg.shape[1], self.GrayImg.shape[0]) else: size = (self.img.shape[1], self.img.shape[0]) fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') self.video_writer = cv2.VideoWriter(video_name, fourcc, self.camera.get(5), size) self.RecordFlag = 1 self.StopBt.setEnabled(False) self.ExitBt.setEnabled(False) elif tag == 'Stop': self.RecordBt.setText('Record') self.video_writer.release() self.RecordFlag = 0 self.StopBt.setEnabled(True) self.ExitBt.setEnabled(True) def drawAvg(self): self.draw_2.clear() img2RGB = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(img2RGB, cv2.COLOR_RGB2GRAY) #初始化numpy arr r_arr = np.zeros((2560, 1), np.uint8) g_arr = np.zeros((2560, 1), np.uint8) b_arr = np.zeros((2560, 1), np.uint8) Gray_arr = np.zeros((2560, 1), np.uint8) r_arr[:, 0] = np.sum( img2RGB[int(self.roi_Y.text( )):int(int(self.roi_Y.text()) + int(self.roi_Height.text())), :, 0], 0) / int(self.roi_Height.text()) g_arr[:, 0] = np.sum( img2RGB[int(self.roi_Y.text( )):int(int(self.roi_Y.text()) + int(self.roi_Height.text())), :, 1], 0) / int(self.roi_Height.text()) b_arr[:, 0] = np.sum( img2RGB[int(self.roi_Y.text( )):int(int(self.roi_Y.text()) + int(self.roi_Height.text())), :, 2], 0) / int(self.roi_Height.text()) Gray_arr[:, 0] = np.sum( gray[int(self.roi_Y.text( )):int(int(self.roi_Y.text()) + int(self.roi_Height.text())), :], 0) / int(self.roi_Height.text()) self.SavePixel_arr = np.zeros( (2560, 2), dtype=np.int) # SavePixel_arr 存pixel和Gray_arr _index = [i for i in range(2560)] self.SavePixel_arr[:, 0] = np.array(_index) self.SavePixel_arr[:, 1] = Gray_arr[:, 0] self.avg = int(self.Avg_logout.text()) #user輸入平均次數 # 如果 getPixel_arr的長度大於10,就把第一筆資料刪除,固定只存10筆資料 if len(self.getPixel_arr) >= self.avg: self.getPixel_arr.pop(0) self.getPixel_arr.append(self.SavePixel_arr) self.add_arr = np.zeros( (2560, 1), dtype=np.float16) #add_arr=[] 存getPixel_arr相加的值 for arr2 in self.getPixel_arr: for ii in range(2560): self.add_arr[ii, 0] = np.add(self.add_arr[ii, 0], arr2[ii, 1]) self.AvgGray_arr = np.zeros((2560, 1), dtype=np.float16) for i in range(2560): self.AvgGray_arr[i, 0] = np.add_arr[ii, 0] / self.avg x = np.linspace(0, 2560, 2560) self.draw_2.setRange(xRange=[0, 2560]) # 固定x軸 不會拉動 self.draw_2.setRange(yRange=[0, 255]) # 固定y軸 不會拉動 self.draw_2.plot(x, r_arr[:, 0], pen='r') self.draw_2.plot(x, g_arr[:, 0], pen='g') self.draw_2.plot(x, b_arr[:, 0], pen='b') self.draw_2.plot(x, self.AvgGray_arrGray_arr[:, 0], pen='w') #self.draw_2.plot(x,Gray_arr[:,0],pen='w') if self.GrayCheck.isChecked(): self.draw_2.clear() self.draw_2.plot(x, self.AvgGray_arrGray_arr[:, 0], pen='w') #self.draw_2.plot(x,Gray_arr[:,0],pen='w') def calculate(self): self.not_open += 1 pixel_array = [] wave_array = [] if self.P1.text(): a1 = float(self.P1.text()) pixel_array.append(a1) if self.W1.text(): b1 = float(self.W1.text()) wave_array.append(b1) if self.P2.text(): a2 = float(self.P2.text()) pixel_array.append(a2) if self.W2.text(): b2 = float(self.W2.text()) wave_array.append(b2) if self.P3.text(): a3 = float(self.P3.text()) pixel_array.append(a3) if self.W3.text(): b3 = float(self.W3.text()) wave_array.append(b3) if self.P4.text(): a4 = float(self.P4.text()) pixel_array.append(a4) if self.W4.text(): b4 = float(self.W4.text()) wave_array.append(b4) if self.P5.text(): a5 = float(self.P5.text()) pixel_array.append(a5) if self.W5.text(): b5 = float(self.W5.text()) wave_array.append(b5) if self.P6.text(): a6 = float(self.P6.text()) pixel_array.append(a6) if self.W6.text(): b6 = float(self.W6.text()) wave_array.append(b6) if self.P7.text(): a7 = float(self.P7.text()) pixel_array.append(a7) if self.W7.text(): b7 = float(self.W7.text()) wave_array.append(b7) if self.P8.text(): a8 = float(self.P8.text()) pixel_array.append(a8) if self.W8.text(): b8 = float(self.W8.text()) wave_array.append(b8) if self.P9.text(): a9 = float(self.P9.text()) pixel_array.append(a9) if self.W9.text(): b9 = float(self.W9.text()) wave_array.append(b9) if self.P10.text(): a10 = float(self.P10.text()) pixel_array.append(a10) if self.W10.text(): b10 = float(self.W9.text()) wave_array.append(b10) x = pixel_array y = wave_array print(x) print(y) num = int(self.comboBox.currentText()) #冪次 parameter = np.polyfit(x, y, num) #求係數 print(parameter) #print(parameter[0]) line = np.poly1d(parameter) # 係數帶入方程式得line print(line) if num == 1: result = "一次方係數:" + str(parameter[0]) + "\n" + "常數項係數:" + str( parameter[1]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.clear() self.graphicsView.plot(x, line(x), pen='g') self.p0 = parameter[0] self.p1 = parameter[1] if num == 2: result = "二次方係數:" + str(parameter[0]) + "\n" + "一次方係數:" + str( parameter[1]) + "\n" + "常數項係數:" + str( parameter[2]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.clear() self.graphicsView.plot(x, line(x), pen='g') self.p0 = parameter[0] self.p1 = parameter[1] self.p2 = parameter[2] if num == 3: result = "三次方係數:" + str(parameter[0]) + "\n" + "二次方係數:" + str( parameter[1]) + "\n" + "一次方係數:" + str( parameter[2]) + "\n" + "常數項係數:" + str( parameter[3]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.clear() self.graphicsView.plot(x, line(x), pen='g') self.p0 = parameter[0] self.p1 = parameter[1] self.p2 = parameter[2] self.p3 = parameter[3] if num == 4: result = "四次方係數:" + str(parameter[0]) + "\n" + "三次方係數:" + str( parameter[1]) + "\n" + "二次方係數:" + str( parameter[2]) + "\n" + "一次方係數:" + str( parameter[3]) + "\n" + "常數項係數:" + str( parameter[4]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.clear() self.graphicsView.plot(x, line(x), pen='g') self.p0 = parameter[0] self.p1 = parameter[1] self.p2 = parameter[2] self.p3 = parameter[3] self.p4 = parameter[4] if num == 5: result = "五次方係數:" + str(parameter[0]) + "\n" + "四次方係數:" + str( parameter[1]) + "\n" + "三次方係數:" + str( parameter[2]) + "\n" + "二次方係數:" + str( parameter[3]) + "\n" + "一次方係數:" + str( parameter[4]) + "\n" + "常數項係數:" + str( parameter[5]) + "\n" + "y=" + str(line) self.results_window.setText(result) self.graphicsView.clear() self.graphicsView.plot(x, line(x), pen='g') self.p0 = parameter[0] self.p1 = parameter[1] self.p2 = parameter[2] self.p3 = parameter[3] self.p4 = parameter[4] self.p5 = parameter[5] def drawAvg_after_calculate(self): self.draw_3.clear() img2RGB = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB) gray = cv2.cvtColor(img2RGB, cv2.COLOR_RGB2GRAY) #初始化numpy arr Gray_arr = np.zeros((2560, 1), np.uint8) Gray_arr[:, 0] = np.sum( gray[int(self.roi_Y.text( )):int(int(self.roi_Y.text()) + int(self.roi_Height.text())), :], 0) / int(self.roi_Height.text()) num = int(self.comboBox.currentText()) if num == 1: x_0 = self.p0 * 0 + self.p1 x_2560 = self.p0 * 2560 + self.p1 _x = np.linspace(x_0, x_2560, 2560) if num == 2: #x_0 = self.p0 * 0 + self.p1 *0 + self.p2 x_0 = math.pow(0, 2) * self.p0 + self.p1 * 0 + self.p2 #x_640 =self.p0 * 640 + self.p1 *640 + self.p2 x_640 = math.pow(2560, 2) * self.p0 + math.pow( 2560, 1) * self.p1 + self.p2 _x = np.linspace(x_0, x_2560, 2560) if num == 3: x_0 = math.pow(0, 3) * self.p0 + math.pow( 0, 2) * self.p1 + math.pow(0, 1) * self.p2 + self.p3 x_2560 = math.pow(2560, 3) * self.p0 + math.pow( 2560, 2) * self.p1 + math.pow(2560, 1) * self.p2 + self.p3 _x = np.linspace(x_0, x_2560, 2560) if num == 4: x_0 = math.pow(0, 4) * self.p0 + math.pow( 0, 3) * self.p1 + math.pow(0, 2) * self.p2 + math.pow( 0, 1) * self.p3 + self.p4 x_2560 = math.pow(2560, 4) * self.p0 + math.pow( 2560, 3) * self.p1 + math.pow(2560, 2) * self.p2 + math.pow( 640, 1) * self.p3 + self.p4 _x = np.linspace(x_0, x_2560, 2560) if num == 5: x_0 = math.pow(0, 5) * self.p0 + math.pow( 0, 4) * self.p1 + math.pow(0, 3) * self.p2 + math.pow( 0, 2) * self.p3 + math.pow(0, 1) * self.p4 + self.p5 x_2560 = math.pow(2560, 5) * self.p0 + math.pow( 2560, 4) * self.p1 + math.pow(2560, 3) * self.p2 + math.pow( 2560, 2) * self.p3 + math.pow(2560, 1) * self.p4 + self.p5 _x = np.linspace(x_0, x_2560, 2560) self.save_arr = np.zeros( (2560, 2), dtype=np.uint32) # save_arr存pixel校正的波長及Gray_arr for i in range(2560): self.save_arr[i, 1] = Gray_arr[i, 0] if num == 1: self.save_arr[i, 0] = self.p0 * i + self.p1 if num == 2: self.save_arr[ i, 0] = math.pow(i, 2) * self.p0 + self.p1 * i + self.p2 if num == 3: self.save_arr[i, 0] = math.pow(i, 3) * self.p0 + math.pow( i, 2) * self.p1 + self.p2 * i + self.p3 if num == 4: self.save_arr[i, 0] = math.pow(i, 4) * self.p0 + math.pow( i, 3) * self.p1 + math.pow( i, 2) * self.p2 + self.p3 * i + self.p4 if num == 5: self.save_arr[i, 0] = math.pow(i, 5) * self.p0 + math.pow( i, 4) * self.p1 + math.pow(i, 3) * self.p2 + math.pow( i, 2) * self.p3 + self.p4 * i + self.p5 self.avg = int(self.Avg_logout.text()) #user輸入平均次數 # 如果 getSave_arr的長度大於10,就把第一筆資料刪除,固定只存10筆資料 if len(self.getSave_arr) >= self.avg: self.getSave_arr.pop(0) self.getSave_arr.append(self.save_arr) self.y_arr = np.zeros((2560, 1), dtype=np.float16) #y_arr = [] #存 getSave_arr相加的值 for arr in self.getSave_arr: for i in range(2560): self.y_arr[i, 0] = np.add(self.y_arr[i, 0], arr[i, 1]) self.AvgGray_arr = np.zeros((2560, 1), dtype=np.float16) for i in range(2560): self.AvgGray_arr[i, 0] = self.y_arr[i, 0] / self.avg self.draw_3.setRange(xRange=[0, x_2560]) # 固定x軸 不會拉動 self.draw_3.setRange(yRange=[np.amin(Gray_arr), np.amax(Gray_arr)]) # 固定y軸 不會拉動 self.draw_3.plot(_x, self.AvgGray_arr[:, 0], pen='w') def saveLog(self): fp = open('wavelength.txt', 'w') fp2 = open('pixel.txt', 'w') # 以下: 存波長對強度 self.y_arr = np.zeros((2560, 1), dtype=np.float16) #y_arr=[] #存 getSave_arr相加的值 for arr in self.getSave_arr: for i in range(2560): self.y_arr[i, 0] = np.add(self.y_arr[i, 0], arr[i, 1]) for i in range(2560): fp.writelines( str(self.save_arr[i, 0]) + ',' + str(self.y_arr[i, 0] / self.avg) + '\n') # 以下:存pixcel對強度 self.add_arr = np.zeros( (2560, 1), dtype=np.float16) #add_arr=[] 存getPixel_arr相加的值 for arr2 in self.getPixel_arr: for ii in range(2560): self.add_arr[ii, 0] = np.add(self.add_arr[ii, 0], arr2[ii, 1]) for ii in range(2560): fp2.writelines( str(self.SavePixel_arr[ii, 0]) + ',' + str(self.add_arr[ii, 0] / self.avg) + '\n') fp.close() fp2.close() print('saving done!') # 匯出的pixel和波長光譜數值,都是有平均過後的 def ExitApp(self): self.Timer.Stop() self.camera.release() QCoreApplication.quit()
class CamShow(QMainWindow, Ui_MainWindow): def __del__(self): try: self.camera.release() # 释放资源 except: return def __init__(self, parent=None): super(CamShow, self).__init__(parent) self.setupUi(self) # self.setWindowFlag(QtCore.Qt.FramelessWindowHint) # 隐藏边框 self.PrepSliders() self.PrepWidgets() self.PrepParameters() self.CallBackFunctions() self.car_debool.setChecked(True) self.remove_img() self.Timer = QTimer() self.Timer.timeout.connect(self.TimerOutFun) def PrepSliders(self): self.RedColorSld.valueChanged.connect(self.RedColorSpB.setValue) self.RedColorSpB.valueChanged.connect(self.RedColorSld.setValue) self.GreenColorSld.valueChanged.connect(self.GreenColorSpB.setValue) self.GreenColorSpB.valueChanged.connect(self.GreenColorSld.setValue) self.BlueColorSld.valueChanged.connect(self.BlueColorSpB.setValue) self.BlueColorSpB.valueChanged.connect(self.BlueColorSld.setValue) self.ExpTimeSld.valueChanged.connect(self.ExpTimeSpB.setValue) self.ExpTimeSpB.valueChanged.connect(self.ExpTimeSld.setValue) self.GainSld.valueChanged.connect(self.GainSpB.setValue) self.GainSpB.valueChanged.connect(self.GainSld.setValue) self.BrightSld.valueChanged.connect(self.BrightSpB.setValue) self.BrightSpB.valueChanged.connect(self.BrightSld.setValue) self.ContrastSld.valueChanged.connect(self.ContrastSpB.setValue) self.ContrastSpB.valueChanged.connect(self.ContrastSld.setValue) def PrepWidgets(self): self.PrepCamera() self.StopBt.setEnabled(False) self.RecordBt.setEnabled(False) self.GrayImgCkB.setEnabled(False) self.RedColorSld.setEnabled(False) self.RedColorSpB.setEnabled(False) self.GreenColorSld.setEnabled(False) self.GreenColorSpB.setEnabled(False) self.BlueColorSld.setEnabled(False) self.BlueColorSpB.setEnabled(False) self.ExpTimeSld.setEnabled(False) self.ExpTimeSpB.setEnabled(False) self.GainSld.setEnabled(False) self.GainSpB.setEnabled(False) self.BrightSld.setEnabled(False) self.BrightSpB.setEnabled(False) self.ContrastSld.setEnabled(False) self.ContrastSpB.setEnabled(False) def PrepCamera(self): try: self.camera = cv2.VideoCapture(0) self.MsgTE.clear() self.MsgTE.append('Oboard camera connected.') self.MsgTE.setPlainText() except Exception as e: self.MsgTE.clear() self.MsgTE.append(str(e)) def PrepParameters(self): self.RecordFlag = 0 self.RecordPath = 'img_save_path/' self.FilePathLE.setText(self.RecordPath) self.Image_num = 0 self.R = 1 self.G = 1 self.B = 1 self.ExpTimeSld.setValue(self.camera.get(15)) self.SetExposure() self.GainSld.setValue(self.camera.get(14)) self.SetGain() self.BrightSld.setValue(self.camera.get(10)) self.SetBrightness() self.ContrastSld.setValue(self.camera.get(11)) self.SetContrast() self.MsgTE.clear() def CallBackFunctions(self): self.FilePathBt.clicked.connect(self.SetFilePath) self.ShowBt.clicked.connect(self.StartCamera) #处理摄像头模式的图像送入车牌识别系统,不断检测文件夹是否有保存的图像 self.ShowBt.clicked.connect(self.choose_cam) self.StopBt.clicked.connect(self.StopCamera) self.RecordBt.clicked.connect(self.RecordCamera) # self.ExitBt.clicked.connect(self.ExitApp) self.GrayImgCkB.stateChanged.connect(self.SetGray) self.ExpTimeSld.valueChanged.connect(self.SetExposure) self.GainSld.valueChanged.connect(self.SetGain) self.BrightSld.valueChanged.connect(self.SetBrightness) self.ContrastSld.valueChanged.connect(self.SetContrast) self.RedColorSld.valueChanged.connect(self.SetR) self.GreenColorSld.valueChanged.connect(self.SetG) self.BlueColorSld.valueChanged.connect(self.SetB) self.img_pat.clicked.connect(self.tanchu1) self.img_pat.clicked.connect(self.choose_img) self.vid_pat.clicked.connect(self.tanchu2) self.vid_pat.clicked.connect(self.remove_img) self.vid_pat.clicked.connect(self.choose_video) self.cam_pat.clicked.connect(self.tanchu3) self.cam_pat.clicked.connect(self.remove_img) self.export_exl.clicked.connect(self.export_jilu) self.remove_file.clicked.connect(self.remove_img) def remove_img_neibu(self): for files in os.listdir('output'): if files.endswith(".jpg"): os.remove(os.path.join('output', files)) def export_jilu(self): jilu_all = self.result_form.toPlainText() print(type(jilu_all), jilu_all) filename_t = f"pl-result-{time.strftime('%m-%d-%H-%M-%S',time.localtime(time.time()))}.txt" fh = open(filename_t, 'w', encoding='utf-8') fh.write(jilu_all) fh.close() def tanchu1(self): self.pattle.setText('单帧模式') def tanchu2(self): self.pattle.setText('视频模式') def tanchu3(self): self.pattle.setText('摄像头模式') def remove_img(self): for files in os.listdir('output'): if files.endswith(".jpg"): os.remove(os.path.join('output', files)) for files in os.listdir('yolo_output'): if files.endswith(".jpg"): os.remove(os.path.join('yolo_output', files)) self.MsgTE.setText("清除缓存!") def choose_cam(self): # # 创建cam显示线程 th1 = threading.Thread(target=self.choose_video1) th1.start() def choose_video(self): vidName, vidType = QFileDialog.getOpenFileName( self, "打开视频", "", "*.mp4;;*.avi;;All Files(*)") self.videoCapture2 = cv2.VideoCapture() self.videoCapture2.open(vidName) print("视频位置::", vidName) self.MsgTE.setText(f"视频位置:{vidName}") # 创建视频显示线程 th1 = threading.Thread(target=self.choose_video1) th1.start() th2 = threading.Thread(target=self.choose_video2) th2.start() def choose_video2(self): timevi2 = time.time() # time.sleep(0.5) # vidName, vidType = QFileDialog.getOpenFileName(self, "打开视频", "", "*.mp4;;*.avi;;All Files(*)") # self.videoCapture2 = cv2.VideoCapture() # self.videoCapture2.open('vid_te.mp4') # fps = self.videoCapture2.get(cv2.CAP_PROP_FPS) # self.FmRateLCD.display(fps) print('success bofang') img_num = 0 while self.videoCapture2.isOpened(): ret, frame = self.videoCapture2.read() if ret: frame1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) qimg = QPixmap(qimage2ndarray.array2qimage(frame1)) self.img_one.setPixmap( qimg.scaled(self.img_one.width(), self.img_one.height())) if img_num % 10 == 0: filename_m = f"car{time.strftime('%m-%d-%H-%M-%S',time.localtime(time.time()))}_{img_num}.jpg" cv2.imwrite(f'output/{filename_m}', frame) else: break img_num += 1 print('vid2:', time.time() - timevi2) def choose_video1(self): time.sleep(1) timev1 = time.time() while (len(os.listdir("output")) != 0): # print("success 1") # print('is detection car: ',self.car_debool.isChecked()) print(len(os.listdir("output"))) filelist = [] for imgfile in os.listdir("output"): filelist.append(imgfile) if self.car_debool.isChecked(): print("批量检测车辆") car_det_res, iscar = ycd.yolo_car_det("output") else: car_det_res = None # for dip_file in os.listdir("yolov3_tiny_car_det/output"): for dip_file in car_det_res: if dip_file is not "none": car_jpg_res = QPixmap( './yolo_output/{}'.format(dip_file)).scaled( self.car_det.width(), self.car_det.height()) self.car_det.setPixmap(car_jpg_res) # 车牌定位开始,需修改,先回去修改单张图片问题 start_time = time.time() print("车牌定位") pr_det_res = pll.location_main(f"yolo_output/{dip_file}") # pr_det_res = None print("车牌识别--", pr_det_res) if pr_det_res: pr_rec_res = plr.inference() now_time = time.time() all_time = datetime.timedelta(seconds=now_time - start_time) print("定位识别-time:", all_time) print("car:", car_det_res) print("pr:", pr_det_res) jpg_res = QPixmap('{}'.format(pr_det_res)).scaled( self.pr_loc.width(), self.pr_loc.height()) self.pr_loc.setPixmap(jpg_res) self.pr_res.setText(pr_rec_res) jilu = time.strftime( "%b %d %Y %H:%M:%S", time.localtime( time.time())) + '车牌号:' + pr_rec_res self.result_form.appendPlainText(jilu) # self.MsgTE.setText("单张图片正常识别!") else: print("none pll") # self.MsgTE.setText("单张图片未检测到车牌!") self.pr_loc.setText('no plate!!!') self.pr_res.setText('no plate!!!') for rmfile in filelist: print("remove,", rmfile) os.remove(f"output/{rmfile}") time.sleep(0.3) print("vid1:", time.time() - timev1) def choose_img(self): imgName, imgType = QFileDialog.getOpenFileName( self, "打开图片", "", "*.jpg;;*.png;;All Files(*)") print("单张图片位置::", imgName) jpg = QPixmap(imgName).scaled(self.img_one.width(), self.img_one.height()) self.img_one.setPixmap(jpg) start_time = time.time() print("车辆检测--") car_det_res, is_car = ycd.yolo_car_det(imgName) print(car_det_res, is_car) print('ok') if is_car: car_jpg_res = QPixmap( './yolo_output/{}'.format(car_det_res)).scaled( self.car_det.width(), self.car_det.height()) self.car_det.setPixmap(car_jpg_res) car_det_res = f'./yolo_output/{car_det_res}' else: self.car_det.setPixmap(jpg) print("车牌定位--") # start_time = time.time() pr_det_res = pll.location_main(imgName) # pr_det_res = None print("车牌识别--") if pr_det_res: pr_rec_res = plr.inference() now_time = time.time() all_time = datetime.timedelta(seconds=now_time - start_time) print("结束-time:", all_time) print("car:", car_det_res) print("pr:", pr_det_res) jpg_res = QPixmap('{}'.format(pr_det_res)).scaled( self.pr_loc.width(), self.pr_loc.height()) self.pr_loc.setPixmap(jpg_res) self.pr_res.setText(pr_rec_res) jilu = time.strftime("%b %d %Y %H:%M:%S", time.localtime( time.time())) + '车牌号:' + pr_rec_res self.result_form.appendPlainText(jilu) self.MsgTE.setText("单张图片正常识别!") else: self.MsgTE.setText("单张图片未检测到车牌!") self.pr_loc.setText('no plate!!!') self.pr_res.setText('no plate!!!') def SetR(self): R = self.RedColorSld.value() self.R = R / 255 def SetG(self): G = self.GreenColorSld.value() self.G = G / 255 def SetB(self): B = self.BlueColorSld.value() self.B = B / 255 def SetContrast(self): contrast_toset = self.ContrastSld.value() try: self.camera.set(11, contrast_toset) self.MsgTE.setPlainText('The contrast is set to ' + str(self.camera.get(11))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetBrightness(self): brightness_toset = self.BrightSld.value() try: self.camera.set(10, brightness_toset) self.MsgTE.setPlainText('The brightness is set to ' + str(self.camera.get(10))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetGain(self): gain_toset = self.GainSld.value() try: self.camera.set(14, gain_toset) self.MsgTE.setPlainText('The gain is set to ' + str(self.camera.get(14))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetExposure(self): try: exposure_time_toset = self.ExpTimeSld.value() self.camera.set(15, exposure_time_toset) self.MsgTE.setPlainText('The exposure time is set to ' + str(self.camera.get(15))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetGray(self): if self.GrayImgCkB.isChecked(): self.RedColorSld.setEnabled(False) self.RedColorSpB.setEnabled(False) self.GreenColorSld.setEnabled(False) self.GreenColorSpB.setEnabled(False) self.BlueColorSld.setEnabled(False) self.BlueColorSpB.setEnabled(False) else: self.RedColorSld.setEnabled(True) self.RedColorSpB.setEnabled(True) self.GreenColorSld.setEnabled(True) self.GreenColorSpB.setEnabled(True) self.BlueColorSld.setEnabled(True) self.BlueColorSpB.setEnabled(True) def StartCamera(self): self.ShowBt.setEnabled(False) self.StopBt.setEnabled(True) self.RecordBt.setEnabled(True) self.GrayImgCkB.setEnabled(True) if self.GrayImgCkB.isChecked() == 0: self.RedColorSld.setEnabled(True) self.RedColorSpB.setEnabled(True) self.GreenColorSld.setEnabled(True) self.GreenColorSpB.setEnabled(True) self.BlueColorSld.setEnabled(True) self.BlueColorSpB.setEnabled(True) self.ExpTimeSld.setEnabled(True) self.ExpTimeSpB.setEnabled(True) self.GainSld.setEnabled(True) self.GainSpB.setEnabled(True) self.BrightSld.setEnabled(True) self.BrightSpB.setEnabled(True) self.ContrastSld.setEnabled(True) self.ContrastSpB.setEnabled(True) self.RecordBt.setText('录像') # self.Timer.start(1) self.timelb = time.clock() def SetFilePath(self): dirname = QFileDialog.getExistingDirectory(self, "浏览", '.') if dirname: self.FilePathLE.setText(dirname) self.RecordPath = dirname + '/' def TimerOutFun(self): success, img = self.camera.read() if success: self.Image = self.ColorAdjust(img) self.DispImg() if self.Image_num % 20 == 0: filename_m = f"car{time.strftime('%m-%d-%H-%M-%S',time.localtime(time.time()))}_{self.Image_num}.jpg" cv2.imwrite(f'output/{filename_m}', self.Image) self.Image_num += 1 if self.RecordFlag: self.video_writer.write(img) if self.Image_num % 10 == 9: frame_rate = 10 / (time.clock() - self.timelb) self.FmRateLCD.display(frame_rate) self.timelb = time.clock() #size=img.shape self.ImgWidthLCD.display(self.camera.get(3)) self.ImgHeightLCD.display(self.camera.get(4)) else: self.MsgTE.clear() self.MsgTE.setPlainText('Image obtaining failed.') def ColorAdjust(self, img): try: B = img[:, :, 0] G = img[:, :, 1] R = img[:, :, 2] B = B * self.B G = G * self.G R = R * self.R img1 = img img1[:, :, 0] = B img1[:, :, 1] = G img1[:, :, 2] = R return img1 except Exception as e: self.MsgTE.setPlainText(str(e)) def DispImg(self): if self.GrayImgCkB.isChecked(): img = cv2.cvtColor(self.Image, cv2.COLOR_BGR2GRAY) else: img = cv2.cvtColor(self.Image, cv2.COLOR_BGR2RGB) qimg = qimage2ndarray.array2qimage(img) self.DispLb.setPixmap(QPixmap(qimg)) self.DispLb.show() def StopCamera(self): if self.StopBt.text() == '暂停': self.StopBt.setText('继续') self.RecordBt.setText('保存') self.Timer.stop() elif self.StopBt.text() == '继续': self.StopBt.setText('暂停') self.RecordBt.setText('录像') self.Timer.start(1) time.sleep(0.5) self.choose_cam() def RecordCamera(self): tag = self.RecordBt.text() if tag == '保存': try: image_name = self.RecordPath + 'image' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.jpg' print(image_name) cv2.imwrite(image_name, self.Image) # jpg = QPixmap(image_name).scaled(self.img_one.width(), self.img_one.height()) # self.img_one.setPixmap(jpg) self.MsgTE.clear() self.MsgTE.setPlainText('Image saved.{}'.format(image_name)) except Exception as e: self.MsgTE.clear() self.MsgTE.setPlainText(str(e)) elif tag == '录像': self.RecordBt.setText('停止') video_name = self.RecordPath + 'video' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.avi' fps = self.FmRateLCD.value() size = (self.Image.shape[1], self.Image.shape[0]) fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') self.video_writer = cv2.VideoWriter(video_name, fourcc, fps, size) self.RecordFlag = 1 self.MsgTE.setPlainText('Video recording...') self.StopBt.setEnabled(False) # self.ExitBt.setEnabled(False) elif tag == '停止': self.RecordBt.setText('录像') self.video_writer.release() self.RecordFlag = 0 self.MsgTE.setPlainText('Video saved.') self.StopBt.setEnabled(True) # self.ExitBt.setEnabled(True) def ExitApp(self): self.Timer.Stop() self.camera.release() self.MsgTE.setPlainText('Exiting the application..') QCoreApplication.quit()
class CamShow(QMainWindow, Ui_MainWindow): def __del__(self): try: self.camera.release() # 释放资源 except: return def __init__(self, parent=None): super(CamShow, self).__init__(parent) self.setupUi(self) self.PrepSliders() self.PrepWidgets() self.PrepParameters() self.CallBackFunctions() self.Timer = QTimer() self.Timer.timeout.connect(self.TimerOutFun) def PrepSliders(self): self.RedColorSld.valueChanged.connect(self.RedColorSpB.setValue) self.RedColorSpB.valueChanged.connect(self.RedColorSld.setValue) self.GreenColorSld.valueChanged.connect(self.GreenColorSpB.setValue) self.GreenColorSpB.valueChanged.connect(self.GreenColorSld.setValue) self.BlueColorSld.valueChanged.connect(self.BlueColorSpB.setValue) self.BlueColorSpB.valueChanged.connect(self.BlueColorSld.setValue) self.ExpTimeSld.valueChanged.connect(self.ExpTimeSpB.setValue) self.ExpTimeSpB.valueChanged.connect(self.ExpTimeSld.setValue) self.GainSld.valueChanged.connect(self.GainSpB.setValue) self.GainSpB.valueChanged.connect(self.GainSld.setValue) self.BrightSld.valueChanged.connect(self.BrightSpB.setValue) self.BrightSpB.valueChanged.connect(self.BrightSld.setValue) self.ContrastSld.valueChanged.connect(self.ContrastSpB.setValue) self.ContrastSpB.valueChanged.connect(self.ContrastSld.setValue) def PrepWidgets(self): self.PrepCamera() self.StopBt.setEnabled(False) self.RecordBt.setEnabled(False) self.GrayImgCkB.setEnabled(False) self.RedColorSld.setEnabled(False) self.RedColorSpB.setEnabled(False) self.GreenColorSld.setEnabled(False) self.GreenColorSpB.setEnabled(False) self.BlueColorSld.setEnabled(False) self.BlueColorSpB.setEnabled(False) self.ExpTimeSld.setEnabled(False) self.ExpTimeSpB.setEnabled(False) self.GainSld.setEnabled(False) self.GainSpB.setEnabled(False) self.BrightSld.setEnabled(False) self.BrightSpB.setEnabled(False) self.ContrastSld.setEnabled(False) self.ContrastSpB.setEnabled(False) def PrepCamera(self): try: self.camera = cv2.VideoCapture(0) self.MsgTE.clear() self.MsgTE.append('Oboard camera connected.') self.MsgTE.setPlainText() except Exception as e: self.MsgTE.clear() self.MsgTE.append(str(e)) def PrepParameters(self): self.RecordFlag = 0 self.RecordPath = 'D:/Python/PyQt/' self.FilePathLE.setText(self.RecordPath) self.Image_num = 0 self.R = 1 self.G = 1 self.B = 1 self.ExpTimeSld.setValue(self.camera.get(15)) self.SetExposure() self.GainSld.setValue(self.camera.get(14)) self.SetGain() self.BrightSld.setValue(self.camera.get(10)) self.SetBrightness() self.ContrastSld.setValue(self.camera.get(11)) self.SetContrast() self.MsgTE.clear() def CallBackFunctions(self): self.FilePathBt.clicked.connect(self.SetFilePath) self.ShowBt.clicked.connect(self.StartCamera) self.StopBt.clicked.connect(self.StopCamera) self.RecordBt.clicked.connect(self.RecordCamera) self.ExitBt.clicked.connect(self.ExitApp) self.GrayImgCkB.stateChanged.connect(self.SetGray) self.ExpTimeSld.valueChanged.connect(self.SetExposure) self.GainSld.valueChanged.connect(self.SetGain) self.BrightSld.valueChanged.connect(self.SetBrightness) self.ContrastSld.valueChanged.connect(self.SetContrast) self.RedColorSld.valueChanged.connect(self.SetR) self.GreenColorSld.valueChanged.connect(self.SetG) self.BlueColorSld.valueChanged.connect(self.SetB) def SetR(self): R = self.RedColorSld.value() self.R = R / 255 def SetG(self): G = self.GreenColorSld.value() self.G = G / 255 def SetB(self): B = self.BlueColorSld.value() self.B = B / 255 def SetContrast(self): contrast_toset = self.ContrastSld.value() try: self.camera.set(11, contrast_toset) self.MsgTE.setPlainText('The contrast is set to ' + str(self.camera.get(11))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetBrightness(self): brightness_toset = self.BrightSld.value() try: self.camera.set(10, brightness_toset) self.MsgTE.setPlainText('The brightness is set to ' + str(self.camera.get(10))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetGain(self): gain_toset = self.GainSld.value() try: self.camera.set(14, gain_toset) self.MsgTE.setPlainText('The gain is set to ' + str(self.camera.get(14))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetExposure(self): try: exposure_time_toset = self.ExpTimeSld.value() self.camera.set(15, exposure_time_toset) self.MsgTE.setPlainText('The exposure time is set to ' + str(self.camera.get(15))) except Exception as e: self.MsgTE.setPlainText(str(e)) def SetGray(self): if self.GrayImgCkB.isChecked(): self.RedColorSld.setEnabled(False) self.RedColorSpB.setEnabled(False) self.GreenColorSld.setEnabled(False) self.GreenColorSpB.setEnabled(False) self.BlueColorSld.setEnabled(False) self.BlueColorSpB.setEnabled(False) else: self.RedColorSld.setEnabled(True) self.RedColorSpB.setEnabled(True) self.GreenColorSld.setEnabled(True) self.GreenColorSpB.setEnabled(True) self.BlueColorSld.setEnabled(True) self.BlueColorSpB.setEnabled(True) def StartCamera(self): self.ShowBt.setEnabled(False) self.StopBt.setEnabled(True) self.RecordBt.setEnabled(True) self.GrayImgCkB.setEnabled(True) if self.GrayImgCkB.isChecked() == 0: self.RedColorSld.setEnabled(True) self.RedColorSpB.setEnabled(True) self.GreenColorSld.setEnabled(True) self.GreenColorSpB.setEnabled(True) self.BlueColorSld.setEnabled(True) self.BlueColorSpB.setEnabled(True) self.ExpTimeSld.setEnabled(True) self.ExpTimeSpB.setEnabled(True) self.GainSld.setEnabled(True) self.GainSpB.setEnabled(True) self.BrightSld.setEnabled(True) self.BrightSpB.setEnabled(True) self.ContrastSld.setEnabled(True) self.ContrastSpB.setEnabled(True) self.RecordBt.setText('录像') self.Timer.start(1) self.timelb = time.clock() def SetFilePath(self): dirname = QFileDialog.getExistingDirectory(self, "浏览", '.') if dirname: self.FilePathLE.setText(dirname) self.RecordPath = dirname + '/' def TimerOutFun(self): success, img = self.camera.read() if success: self.Image = self.ColorAdjust(img) #self.Image=img self.DispImg() self.Image_num += 1 if self.RecordFlag: self.video_writer.write(img) if self.Image_num % 10 == 9: frame_rate = 10 / (time.clock() - self.timelb) self.FmRateLCD.display(frame_rate) self.timelb = time.clock() #size=img.shape self.ImgWidthLCD.display(self.camera.get(3)) self.ImgHeightLCD.display(self.camera.get(4)) else: self.MsgTE.clear() self.MsgTE.setPlainText('Image obtaining failed.') def ColorAdjust(self, img): try: B = img[:, :, 0] G = img[:, :, 1] R = img[:, :, 2] B = B * self.B G = G * self.G R = R * self.R #B.astype(cv2.PARAM_UNSIGNED_INT) #G.astype(cv2.PARAM_UNSIGNED_INT) #R.astype(cv2.PARAM_UNSIGNED_INT) img1 = img img1[:, :, 0] = B img1[:, :, 1] = G img1[:, :, 2] = R return img1 except Exception as e: self.MsgTE.setPlainText(str(e)) def DispImg(self): if self.GrayImgCkB.isChecked(): img = cv2.cvtColor(self.Image, cv2.COLOR_BGR2GRAY) else: img = cv2.cvtColor(self.Image, cv2.COLOR_BGR2RGB) qimg = qimage2ndarray.array2qimage(img) self.DispLb.setPixmap(QPixmap(qimg)) self.DispLb.show() def StopCamera(self): if self.StopBt.text() == '暂停': self.StopBt.setText('继续') self.RecordBt.setText('保存') self.Timer.stop() elif self.StopBt.text() == '继续': self.StopBt.setText('暂停') self.RecordBt.setText('录像') self.Timer.start(1) def RecordCamera(self): tag = self.RecordBt.text() if tag == '保存': try: image_name = self.RecordPath + 'image' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.jpg' print(image_name) cv2.imwrite(image_name, self.Image) self.MsgTE.clear() self.MsgTE.setPlainText('Image saved.') except Exception as e: self.MsgTE.clear() self.MsgTE.setPlainText(str(e)) elif tag == '录像': self.RecordBt.setText('停止') video_name = self.RecordPath + 'video' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.avi' fps = self.FmRateLCD.value() size = (self.Image.shape[1], self.Image.shape[0]) fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') self.video_writer = cv2.VideoWriter(video_name, fourcc, self.camera.get(5), size) self.RecordFlag = 1 self.MsgTE.setPlainText('Video recording...') self.StopBt.setEnabled(False) self.ExitBt.setEnabled(False) elif tag == '停止': self.RecordBt.setText('录像') self.video_writer.release() self.RecordFlag = 0 self.MsgTE.setPlainText('Video saved.') self.StopBt.setEnabled(True) self.ExitBt.setEnabled(True) def ExitApp(self): self.Timer.Stop() self.camera.release() self.MsgTE.setPlainText('Exiting the application..') QCoreApplication.quit()
class RMS_show(QMainWindow, Ui_RMS): def __init__(self, parent=None): super(RMS_show, self).__init__(parent) self.setupUi(self) self.PrepWidgets() self.Timer = QTimer() self.CallBackFunctions() #ros节点定义,并创建订阅者与发布者 rospy.init_node('RMS_UI', anonymous=True) rate = rospy.Rate(10) # 10hz self.pathfollowing_pub = rospy.Publisher('/waypoints', UInt64MultiArray, queue_size=10) self.positionkeeping_pub = rospy.Publisher('/set_point', UInt64MultiArray, queue_size=10) rospy.Subscriber("/position_real", UInt64MultiArray, self.Position_show) rate.sleep() def PrepWidgets(self): self.checkBox_1.setEnabled(True) self.checkBox_2.setEnabled(True) self.PushButton_start.setEnabled(False) self.PushButton_suspend.setEnabled(False) self.PushButton_save.setEnabled(False) self.PushButton_quit.setEnabled(False) self.PositionKeeping_Lat.setEnabled(False) self.PositionKeeping_Lon.setEnabled(False) self.Point1_Lat.setEnabled(False) self.Point1_Lon.setEnabled(False) self.Point2_Lat.setEnabled(False) self.Point2_Lon.setEnabled(False) self.Point3_Lat.setEnabled(False) self.Point3_Lon.setEnabled(False) self.Point4_Lat.setEnabled(False) self.Point4_Lon.setEnabled(False) self.Point5_Lat.setEnabled(False) self.Point5_Lon.setEnabled(False) def checkBox_1_fun(self): if self.checkBox_1.isChecked(): self.PushButton_start.setEnabled(True) self.PositionKeeping_Lat.setEnabled(True) self.PositionKeeping_Lon.setEnabled(True) self.Point1_Lat.setEnabled(False) self.Point1_Lon.setEnabled(False) self.Point2_Lat.setEnabled(False) self.Point2_Lon.setEnabled(False) self.Point3_Lat.setEnabled(False) self.Point3_Lon.setEnabled(False) self.Point4_Lat.setEnabled(False) self.Point4_Lon.setEnabled(False) self.Point5_Lat.setEnabled(False) self.Point5_Lon.setEnabled(False) else: self.PositionKeeping_Lat.setEnabled(False) self.PositionKeeping_Lon.setEnabled(False) def checkBox_2_fun(self): if self.checkBox_2.isChecked(): self.PushButton_start.setEnabled(True) self.PositionKeeping_Lat.setEnabled(False) self.PositionKeeping_Lon.setEnabled(False) self.Point1_Lat.setEnabled(True) self.Point1_Lon.setEnabled(True) self.Point2_Lat.setEnabled(True) self.Point2_Lon.setEnabled(True) self.Point3_Lat.setEnabled(True) self.Point3_Lon.setEnabled(True) self.Point4_Lat.setEnabled(True) self.Point4_Lon.setEnabled(True) self.Point5_Lat.setEnabled(True) self.Point5_Lon.setEnabled(True) else: self.Point1_Lat.setEnabled(False) self.Point1_Lon.setEnabled(False) self.Point2_Lat.setEnabled(False) self.Point2_Lon.setEnabled(False) self.Point3_Lat.setEnabled(False) self.Point3_Lon.setEnabled(False) self.Point4_Lat.setEnabled(False) self.Point4_Lon.setEnabled(False) self.Point5_Lat.setEnabled(False) self.Point5_Lon.setEnabled(False) def Start(self): self.PushButton_start.setEnabled(False) self.PushButton_suspend.setEnabled(True) self.PushButton_save.setEnabled(True) self.PushButton_quit.setEnabled(True) self.checkBox_1.setEnabled(False) self.checkBox_2.setEnabled(False) self.PositionKeeping_Lat.setEnabled(False) self.PositionKeeping_Lon.setEnabled(False) self.Point1_Lat.setEnabled(False) self.Point1_Lon.setEnabled(False) self.Point2_Lat.setEnabled(False) self.Point2_Lon.setEnabled(False) self.Point3_Lat.setEnabled(False) self.Point3_Lon.setEnabled(False) self.Point4_Lat.setEnabled(False) self.Point4_Lon.setEnabled(False) self.Point5_Lat.setEnabled(False) self.Point5_Lon.setEnabled(False) self.textEdit.setText('开始') if self.checkBox_1.isChecked(): try: setpoint = millerToXY(self.PositionKeeping_Lon.value(), self.PositionKeeping_Lat.value()) setpoint_xy = [-setpoint[1], setpoint[0]] self.positionkeeping_pub.publish(setpoint_xy) rospy.loginfo("setpoint is :: %f", setpoint_xy) except Exception: self.textEdit.setText("Fail to load set point") elif self.checkBox_2.isChecked(): try: Point1_xy = millerToXY(self.Point1_Lon.value(), self.Point1_Lat.value()) Point2_xy = millerToXY(self.Point2_Lon.value(), self.Point2_Lat.value()) Point3_xy = millerToXY(self.Point3_Lon.value(), self.Point3_Lat.value()) Point4_xy = millerToXY(self.Point4_Lon.value(), self.Point4_Lat.value()) Point5_xy = millerToXY(self.Point5_Lon.value(), self.Point5_Lat.value()) waypoints_xy = np.array([[-Point1_xy[1], Point1_xy[0]], [-Point2_xy[1], Point2_xy[0]], [-Point3_xy[1], Point3_xy[0]], [-Point4_xy[1], Point4_xy[0]], [-Point5_xy[1], Point5_xy[0]]]) self.pathfollowing_pub.publish(waypoints_xy) rospy.loginfo("pointsway is set as:: %f", waypoints_xy) except Exception: self.textEdit.setText("Fail to load waypoints") def Suspend(self): self.PushButton_start.setEnabled(True) self.PushButton_suspend.setEnabled(False) self.PushButton_save.setEnabled(True) self.PushButton_quit.setEnabled(True) self.checkBox_1.setEnabled(True) self.checkBox_2.setEnabled(True) def ExitApp(self): self.Timer.Stop() self.textEdit.setPlainText('Exiting the application..') QCoreApplication.quit() def Showtime(self): time = QDateTime.currentDateTime() timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd") self.Date.setText(timeDisplay) def Position_show(self, data): global Lat_real_get Lat_real_get = data.data[0] global Lon_real_get Lon_real_get = data.data[1] self.Lat_real.setValue(Lat_real_get) self.Lon_real.setValue(Lon_real_get) def CallBackFunctions(self): self.Timer.timeout.connect(self.Showtime) self.PushButton_start.clicked.connect(self.Start) self.PushButton_suspend.clicked.connect(self.Suspend) self.PushButton_quit.clicked.connect(self.ExitApp) self.checkBox_1.clicked.connect(self.checkBox_1_fun) self.checkBox_2.clicked.connect(self.checkBox_2_fun)
class CamShow(QMainWindow, Ui_CamShow): def __init__(self, parent=None): super(CamShow, self).__init__(parent) self.setupUi(self) self.PrepWidgets() self.PrepParameters() self.CallBackFunctions() self.Timer = QTimer() self.Timer.timeout.connect(self.TimerOutFun) self.stopbt = 0 self.AvgPlot.plotItem.showGrid(True, True, 0.7) #控件初始化 def PrepWidgets(self): self.PrepCamera() self.StopBt.setEnabled(False) self.RecordBt.setEnabled(False) def PrepCamera(self): self.camera = cv2.VideoCapture(0) def PrepParameters(self): self.RecordFlag = 0 self.RecordPath = 'D:/Python/PyQt/' self.FilePathLE.setText(self.RecordPath) self.Image_num = 0 def CallBackFunctions(self): self.FilePathBt.clicked.connect(self.SetFilePath) self.ShowBt.clicked.connect(self.StartCamera) self.StopBt.clicked.connect(self.StopCamera) self.RecordBt.clicked.connect(self.RecordCamera) self.ExitBt.clicked.connect(self.ExitApp) self.btnUpdate.clicked.connect(self.update) def StartCamera(self): self.ShowBt.setEnabled(False) self.StopBt.setEnabled(True) self.RecordBt.setEnabled(True) self.RecordBt.setText('Record') self.Timer.start(1) self.timelb = time.clock() def StopCamera(self): if self.StopBt.text() == 'Stop': self.StopBt.setText('Continue') #self.stopbt = 0 self.RecordBt.setText('Save Pic') self.Timer.stop() else: self.StopBt.setText('Stop') #self.stopbt = 1 self.RecordBt.setText('Record') self.Timer.start(1) def TimerOutFun(self): success, self.img = self.camera.read() self.gray = cv2.cvtColor(self.img, cv2.COLOR_RGB2GRAY) #轉灰階 if success: #self.Image = self.ColorAdjust(img) self.DispImg() self.CopyImg() #self.Image_num+=1 if self.RecordFlag: self.video_writer.write(self.img) def CopyImg(self): ret = QRect(50, 200, 411, 10) CVimg = cv2.cvtColor(self.gray, cv2.COLOR_BGR2RGB) qimg = qimage2ndarray.array2qimage(CVimg) b = qimg.copy(ret) self.DispCopyImg.setPixmap(QPixmap(b)) self.DispCopyImg.show() def DispImg(self): CVimg = cv2.cvtColor(self.gray, cv2.COLOR_BGR2RGB) qimg = qimage2ndarray.array2qimage(CVimg) self.DispLb.setPixmap(QPixmap(qimg)) self.DispLb.show() def SetFilePath(self): dirname = QFileDialog.getExistingDirectory(self, "瀏覽", '.') if dirname: self.FilePathLE.setText(dirname) self.RecordPath = dirname + '/' def RecordCamera(self): tag = self.RecordBt.text() if tag == 'Save Pic': image_name = self.RecordPath + 'self.image' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.jpg' print(image_name) cv2.imwrite(image_name, self.img) elif tag == 'Record': self.RecordBt.setText('Stop') video_name = self.RecordPath + 'video' + time.strftime( '%Y%m%d%H%M%S', time.localtime(time.time())) + '.avi' size = (self.img.shape[1], self.img.shape[0]) fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') self.video_writer = cv2.VideoWriter(video_name, fourcc, self.camera.get(5), size) self.RecordFlag = 1 self.StopBt.setEnabled(False) self.ExitBt.setEnabled(False) elif tag == 'Stop': self.RecordBt.setText('Record') self.video_writer.release() self.RecordFlag = 0 self.StopBt.setEnabled(True) self.ExitBt.setEnabled(True) def showUpdate(self): t = time.clock() points = 100 #number of data points X = np.arange(points) Y = np.sin(np.arange(points) / points * 3 * np.pi + time.time()) C = pyqtgraph.hsvColor(time.time() / 5 % 1, alpha=.5) pen = pyqtgraph.mkPen(color=C, width=5) self.AvgPlot.plot(X, Y, pen=pen, clear=True) def update(self): t1 = time.clock() points = 100 #number of data points X = np.arange(points) Y = np.sin(np.arange(points) / points * 3 * np.pi + time.time()) C = pyqtgraph.hsvColor(time.time() / 5 % 1, alpha=.5) pen = pyqtgraph.mkPen(color=C, width=5) self.AvgPlot.plot(X, Y, pen=pen, clear=True) print("update took %.02f ms" % ((time.clock() - t1) * 1000)) QtCore.QTimer.singleShot(1, self.update) # QUICKLY repeat def ExitApp(self): self.Timer.Stop() self.camera.release() QCoreApplication.quit()