results = self.model_predict(frame) dets = [] if len(results) == 0: pass else: for index, row in results.iterrows(): class_ids = row['class'] scores = float(row['confidence']) x1 = int(row['xmin']) y1 = int(row['ymin']) x2 = int(row['xmax']) y2 = int(row['ymax']) cx = int((x1 + x2)/2) cy = int((y1 + y2)/2) pt_center = (cx,cy) dist = cv2.pointPolygonTest(pts, pt_center, False) if dist > 0: print('在内部') dets.append([x1,y1,x2,y2,scores]) else: print('在外部') 找出为外部的,删除result值

时间: 2024-02-10 14:32:26 浏览: 32
您的问题是如何找出为外部的并删除result值? 在上述代码中,找出为外部的结果是通过计算目标中心点到多边形的距离(dist)来实现的,如果距离大于0,则说明目标不在多边形内部,需要将其删除。可以使用以下代码来实现: ``` to_delete = [] for index, row in results.iterrows(): class_ids = row['class'] scores = float(row['confidence']) x1 = int(row['xmin']) y1 = int(row['ymin']) x2 = int(row['xmax']) y2 = int(row['ymax']) cx = int((x1 + x2)/2) cy = int((y1 + y2)/2) pt_center = (cx,cy) dist = cv2.pointPolygonTest(pts, pt_center, False) if dist > 0: print('在外部') to_delete.append(index) else: print('在内部') results = results.drop(to_delete) ``` 这段代码会遍历所有的结果,如果发现目标不在多边形内部,则将其对应的索引添加到一个列表中,遍历完所有结果后,再将这些索引对应的结果从results中删除。
相关问题

self.about_frame = AboutFrame(self.root) self.log_frame = LogFrame(self.root) menubar = tk.Menu(self.root) menubar.add_command(label='预测', command=self.show_predict) menubar.add_command(label='查询', command=self.show_log) menubar.add_command(label='关于', command=self.show_about) self.root['menu'] = menubar # self.predict_frame = tk.Frame(self.root).pack()为链式结构,实际上将predict_frame变量赋值为None self.predict_frame = tk.Frame(self.root) self.image_label = tk.Label(self.predict_frame) self.image_label.grid(row=1, column=0, pady=10) # pic_path更新 self.text_var.set(self.pic_path) # tk.Label(self.predict_frame, textvariable=self.text_var).grid(row=0, column=0, pady=10) tk.Button(self.predict_frame, text='预测', command=lambda: self.predict_button(self.pic_path), padx=30, pady=20).grid(row=1, column=1, padx=50, pady=10) tk.Button(self.predict_frame, text='预测', command=lambda: self.predict_button(self.pic_path), padx=30, pady=20).grid(row=2, column=1, padx=50, pady=10) tk.Button(self.predict_frame, text='读取文件', command=lambda: self.update_image(self.image_label), padx=30, pady=20).grid(row=1, column=2, padx=10, pady=10) self.predict_frame.pack() # 在predict_frame中内嵌条形图 self.fig = Figure(figsize=(5, 3), dpi=100) self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(self.fig, master=self.predict_frame) # columnspan用于指明占用多列 self.canvas.get_tk_widget().grid(row=3, column=0, columnspan=3)添加拍摄功能,并将拍摄图像在image_label中展示

要添加拍摄功能,并将拍摄图像在`image_label`中展示,可以使用`cv2`库读取摄像头拍摄的图像,并将其转换为`Tkinter`图像格式。以下是一个示例代码: ``` import cv2 from PIL import Image, ImageTk # 添加拍摄功能的函数 def capture_image(): cap = cv2.VideoCapture(0) ret, frame = cap.read() cap.release() if ret: # 将OpenCV图像转换为PIL图像 pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) # 将PIL图像转换为Tkinter图像 tk_image = ImageTk.PhotoImage(pil_image) # 在image_label中展示图像 image_label.config(image=tk_image) image_label.image = tk_image ``` 在上述代码中,`capture_image()`函数使用`cv2.VideoCapture()`函数读取摄像头拍摄的图像。然后,使用`PIL`库将OpenCV图像转换为PIL图像,并使用`ImageTk`模块将其转换为Tkinter图像。最后,将Tkinter图像展示在`image_label`中。 要将`capture_image()`函数添加到界面中,可以在`predict_frame`中添加一个`Button`,并将其命令设置为`capture_image`函数: ``` tk.Button(self.predict_frame, text='拍摄', command=capture_image, padx=30, pady=20).grid(row=2, column=2, padx=10, pady=10) ``` 这将在预测界面中添加一个名为“拍摄”的按钮,单击该按钮将调用`capture_image()`函数,并在`image_label`中展示拍摄的图像。

self.predict_y = self.reg.predict(_X) AttributeError: 'NoneType' object has no attribute 'predict'

This error message suggests that the object "self.reg" is of type "NoneType", which means it has no attribute called "predict". Therefore, when the code tries to call the "predict" method on "self.reg", it raises an AttributeError. To fix this error, you need to make sure that "self.reg" is initialized properly and is not None. You can check if "self.reg" is None by adding a print statement before the line that raises the error: ``` print(self.reg) # add this line to check if self.reg is None self.predict_y = self.reg.predict(_X) ``` If the output of the print statement is "None", then you need to initialize "self.reg" before calling the "predict" method. For example, if you are using scikit-learn's linear regression model, you can initialize "self.reg" as follows: ``` from sklearn.linear_model import LinearRegression class MyModel: def __init__(self): self.reg = LinearRegression() def fit(self, X, y): self.reg.fit(X, y) def predict(self, X): _X = self._transform(X) self.predict_y = self.reg.predict(_X) return self.predict_y ``` This initializes "self.reg" to a new instance of the LinearRegression class, which has the "predict" method you need to call later.

相关推荐

修改以下代码使其能够输出模型预测结果: def open_image(self): file_dialog = QFileDialog() file_paths, _ = file_dialog.getOpenFileNames(self, "选择图片", "", "Image Files (*.png *.jpg *.jpeg)") if file_paths: self.display_images(file_paths) def preprocess_images(self, image_paths): data_transform = transforms.Compose([ transforms.CenterCrop(150), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) self.current_image_paths = [] images = [] for image_path in image_paths: image = Image.open(image_path) image = data_transform(image) image = torch.unsqueeze(image, dim=0) images.append(image) self.current_image_paths.append(image_path) return images def predict_images(self): if not self.current_image_paths: return for i, image_path in enumerate(self.current_image_paths): image = self.preprocess_image(image_path) output = self.model(image) predicted_class = self.class_dict[output.argmax().item()] self.result_labels[i].setText(f"Predicted Class: {predicted_class}") self.progress_bar.setValue((i+1)*20) def display_images(self, image_paths): for i, image_path in enumerate(image_paths): image = QImage(image_path) image = image.scaled(300, 300, Qt.KeepAspectRatio) if i == 0: self.image_label_1.setPixmap(QPixmap.fromImage(image)) elif i == 1: self.image_label_2.setPixmap(QPixmap.fromImage(image)) elif i == 2: self.image_label_3.setPixmap(QPixmap.fromImage(image)) elif i == 3: self.image_label_4.setPixmap(QPixmap.fromImage(image)) elif i == 4: self.image_label_5.setPixmap(QPixmap.fromImage(image))

下面的这段python代码,哪里有错误,修改一下:import numpy as np import matplotlib.pyplot as plt import pandas as pd import torch import torch.nn as nn from torch.autograd import Variable from sklearn.preprocessing import MinMaxScaler training_set = pd.read_csv('CX2-36_1971.csv') training_set = training_set.iloc[:, 1:2].values def sliding_windows(data, seq_length): x = [] y = [] for i in range(len(data) - seq_length): _x = data[i:(i + seq_length)] _y = data[i + seq_length] x.append(_x) y.append(_y) return np.array(x), np.array(y) sc = MinMaxScaler() training_data = sc.fit_transform(training_set) seq_length = 1 x, y = sliding_windows(training_data, seq_length) train_size = int(len(y) * 0.8) test_size = len(y) - train_size dataX = Variable(torch.Tensor(np.array(x))) dataY = Variable(torch.Tensor(np.array(y))) trainX = Variable(torch.Tensor(np.array(x[1:train_size]))) trainY = Variable(torch.Tensor(np.array(y[1:train_size]))) testX = Variable(torch.Tensor(np.array(x[train_size:len(x)]))) testY = Variable(torch.Tensor(np.array(y[train_size:len(y)]))) class LSTM(nn.Module): def __init__(self, num_classes, input_size, hidden_size, num_layers): super(LSTM, self).__init__() self.num_classes = num_classes self.num_layers = num_layers self.input_size = input_size self.hidden_size = hidden_size self.seq_length = seq_length self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, num_classes) def forward(self, x): h_0 = Variable(torch.zeros( self.num_layers, x.size(0), self.hidden_size)) c_0 = Variable(torch.zeros( self.num_layers, x.size(0), self.hidden_size)) # Propagate input through LSTM ula, (h_out, _) = self.lstm(x, (h_0, c_0)) h_out = h_out.view(-1, self.hidden_size) out = self.fc(h_out) return out num_epochs = 2000 learning_rate = 0.001 input_size = 1 hidden_size = 2 num_layers = 1 num_classes = 1 lstm = LSTM(num_classes, input_size, hidden_size, num_layers) criterion = torch.nn.MSELoss() # mean-squared error for regression optimizer = torch.optim.Adam(lstm.parameters(), lr=learning_rate) # optimizer = torch.optim.SGD(lstm.parameters(), lr=learning_rate) runn = 10 Y_predict = np.zeros((runn, len(dataY))) # Train the model for i in range(runn): print('Run: ' + str(i + 1)) for epoch in range(num_epochs): outputs = lstm(trainX) optimizer.zero_grad() # obtain the loss function loss = criterion(outputs, trainY) loss.backward() optimizer.step() if epoch % 100 == 0: print("Epoch: %d, loss: %1.5f" % (epoch, loss.item())) lstm.eval() train_predict = lstm(dataX) data_predict = train_predict.data.numpy() dataY_plot = dataY.data.numpy() data_predict = sc.inverse_transform(data_predict) dataY_plot = sc.inverse_transform(dataY_plot) Y_predict[i,:] = np.transpose(np.array(data_predict)) Y_Predict = np.mean(np.array(Y_predict)) Y_Predict_T = np.transpose(np.array(Y_Predict))

最新推荐

recommend-type

vb仓库管理系统(可执行程序+源码+ 开题报告+ 答辩稿)【VB】.zip

vb仓库管理系统(可执行程序+源码+ 开题报告+ 答辩稿)【VB】
recommend-type

中文翻译Introduction to Linear Algebra, 5th Edition 2.1节

中文翻译Introduction to Linear Algebra, 5th Edition 2.1节 线性代数的核心问题是求解方程组。这些方程都是线性的,即未知数仅与数相乘——我们绝不会 遇见 x 乘以 y。我们的第一个线性方程组较小。接下来你来看看它引申出多远: 两个方程 两个未知数 x − 2y = 1 3x + 2y = 11 (1) 我们一次从一个行开始。第一个方程 x − 2y = 1 得出了 xy 平面的一条直线。由于点 x = 1, y = 0 解 出该方程,因此它在这条直线上。因为 3 − 2 = 1,所以点 x = 3, y = 1 也在这条直线上。若我们选择 x = 101,那我们求出 y = 50。 这条特定直线的斜率是 12,是因为当 x 变化 2 时 y 增加 1。斜率在微积分中很重要,然而这是线 性代数! 图 2.1 将展示第一条直线 x − 2y = 1。此“行图”中的第二条直线来自第二个方程 3x + 2y = 11。你 不能错过两条线的交点 x = 3, y = 1。点 (3, 1) 位于两条线上并且解出两个方程。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

识别MATLAB微分方程求解中的混沌行为:分析非线性方程混沌行为的实用技巧

![matlab求解微分方程](https://img-blog.csdnimg.cn/2021062810300367.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTQ3OTY3OA==,size_16,color_FFFFFF,t_70) # 1. MATLAB微分方程求解概述 微分方程是描述物理、工程和金融等领域中动态系统的数学模型。MATLAB提供了强大的工具来求解微分方程,包括内置求解器和自定义函数
recommend-type

physon如何做ERP系统

作为一个AI语言模型,我可以给您提供一些基本的建议和思路: 1.明确需求和目标:在开始开发ERP系统之前,需要明确您的业务需求和目标,了解您的业务流程、流程数据、员工角色和权限、财务管理等方面的要求,这样才能更好的设计和开发ERP系统。 2.选择技术框架和开发工具:选择合适的技术框架和开发工具是ERP系统开发的关键。选择一种流行的技术框架和工具可以提高开发效率和质量。 3.设计数据库:ERP系统需要一个功能强大的数据库来存储数据。设计数据库需要考虑数据的完整性、安全性和可扩展性。 4.设计系统架构:系统架构是ERP系统的骨架,需要考虑系统的可扩展性、可维护性和性能。 5.开发和测试:
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

探索MATLAB微分方程求解中的分岔分析:揭示方程动态行为的秘密

![matlab求解微分方程](https://img-blog.csdnimg.cn/2021062810300367.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTQ3OTY3OA==,size_16,color_FFFFFF,t_70) # 1. MATLAB微分方程求解概述 微分方程在科学、工程和金融等领域有着广泛的应用。MATLAB作为一种强大的数值计算软件,提供了丰富的微分方程求解工具。本章将概述
recommend-type

ic验证工作中如何在平台中加入发数的总数?

在进行IC验证工作时,可以通过以下步骤在平台中加入发数的总数: 1. 打开IC验证工具(如Cadence Virtuoso)并打开对应的设计文件。 2. 在设计文件中选择需要计算发数的部分电路或模块。 3. 在IC验证工具中打开时序分析工具(如Cadence Tempus)。 4. 在时序分析工具中设置好时钟频率、时钟周期等参数。 5. 执行时序分析,生成时序报告。 6. 在时序报告中查找发数统计信息,将其记录下来。 7. 将发数统计信息添加到平台中,以便在之后的仿真或验证中使用。 需要注意的是,发数统计信息可能因为设计文件的不同而有所差异,需要根据实际情况进行调整和计算。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。