def image_play(self): current_image = Image.open('./movie/img.png').resize((512, 384)) # 打开图片文件并转换为Image对象 imgtk = ImageTk.PhotoImage(image=current_image) # 将Image对象转换为ImageTk.PhotoImage对象 self.lmain.imgtk = imgtk self.lmain.config(image=imgtk)报错image "pyimage18" doesn't exist

时间: 2024-03-28 07:39:32 浏览: 24
这个错误是因为在设置图片时,Tkinter找不到对应的图片对象。可能是因为图片路径不正确或者图片对象没有被正确地创建。你可以尝试检查图片路径是否正确,并且确认图片对象已经被正确地创建。你也可以尝试重新运行程序来创建新的图片对象。如果问题仍然存在,你可以考虑使用其他的图片显示方式,比如Pillow库的ImageTk.PhotoImage方法。
相关问题

程序无法执行,修改class Processor(): def __init__(self): self._inspect_step = int(cfg.get('PROCESS', 'INSPECT_STEP')) def capture_img(self): global aco aco = aco + 1 self._cam.stream_on() raw_image = self._cam.data_stream[0].get_image() if raw_image is None: print("Getting image failed.\n") return None print("Frame ID: {} Height: {} Width: {} Count: {}\n" .format(raw_image.get_frame_id(), raw_image.get_height(), raw_image.get_width(), aco - 2)) numpy_image = raw_image.get_numpy_array() if numpy_image is None: return None img = Image.fromarray(numpy_image, 'L') if self._issave: picfile = '{}/{}.bmp'.format(self._picpath, self._piccount) self._piccount = self._piccount + 1 img.save(picfile) if self._isshow: w, h = img.size scale = min(1.0 * IMG_RESIZE_W / w, 1.0 * IMG_RESIZE_H / h) self._img = ImageTk.PhotoImage(image=img.resize((int(w * scale), int(h * scale)), Image.ANTIALIAS)) self._show_cb(self._img) self._cam.stream_off() return img def process_img(self, img): return PROC_OK def inspect(self): print("process2") time.sleep(1) def rotate(self): count = 0 aco = 0 self.threadsignal = 0 while self._running: v = self._dgl.qpin(ROT) if len(v) > 0: count = count + sum(v) if count > self._inspect_step: aco += 1 img = self.capture_img() count = count - self._inspect_step if __name__ == '__main__': task2 = multiprocessing.Process(target=self.inspect) task2.start() task1 = multiprocessing.Process(target=self.rotate) task1.start()

在这段代码中,有几个问题可以被改进。首先,类 `Processor` 中的全局变量 `aco` 可能会导致并发问题,在多进程环境下应该避免使用全局变量。其次,代码中出现了 `time.sleep()`,这会阻塞当前进程并造成性能瓶颈,应该尽量避免使用。 以下是可能的改进方案: 1. 将 `aco` 变量改为实例变量,避免多进程之间的并发问题。 2. 使用 `Queue` 或其他进程间通信机制替代全局变量,避免多进程之间的竞争。 3. 将 `time.sleep()` 改为使用定时器或者事件,避免阻塞进程并提高程序的性能。 4. 在多进程环境中,使用 `if __name__ == '__main__':` 来避免创建子进程时出现递归调用的问题。 以下是修改后的代码示例: ```python import multiprocessing from queue import Queue import time class Processor(): def __init__(self): self._inspect_step = int(cfg.get('PROCESS', 'INSPECT_STEP')) self._aco = 0 self._queue = Queue() def capture_img(self): self._aco += 1 self._cam.stream_on() raw_image = self._cam.data_stream[0].get_image() if raw_image is None: print("Getting image failed.\n") return None print("Frame ID: {} Height: {} Width: {} Count: {}\n".format(raw_image.get_frame_id(), raw_image.get_height(), raw_image.get_width(), self._aco - 2)) numpy_image = raw_image.get_numpy_array() if numpy_image is None: return None img = Image.fromarray(numpy_image, 'L') if self._issave: picfile = '{}/{}.bmp'.format(self._picpath, self._piccount) self._piccount = self._piccount + 1 img.save(picfile) if self._isshow: w, h = img.size scale = min(1.0 * IMG_RESIZE_W / w, 1.0 * IMG_RESIZE_H / h) self._img = ImageTk.PhotoImage(image=img.resize((int(w * scale), int(h * scale)), Image.ANTIALIAS)) self._show_cb(self._img) self._cam.stream_off() return img def process_img(self, img): return PROC_OK def inspect(self): print("process2") while self._running: time.sleep(1) self._queue.put("task") def rotate(self): count = 0 while self._running: v = self._dgl.qpin(ROT) if len(v) > 0: count = count + sum(v) if count > self._inspect_step: self._aco += 1 img = self.capture_img() count = count - self._inspect_step try: task = self._queue.get(block=False) if task == "task": print("processing task") except: pass if __name__ == '__main__': p = Processor() p._running = True task2 = multiprocessing.Process(target=p.inspect) task2.start() task1 = multiprocessing.Process(target=p.rotate) task1.start() ``` 请注意,这里只是对原始代码的一些修改建议,并不能保证这样的修改能够完全解决问题。在实际环境中,还需要根据具体情况进行调整和优化。

将下面读取视频的代码改为读取播放图片 def confirm_action(self): self.cap1 = cv2.VideoCapture(self.addressentry.get()) self.key = 1 self.video_play() # 视频文件播放 def video_play(self): self.wait_time = 1000 / 60 # 设置帧率 这里设置的是60帧 while self.cap1.isOpened(): ret, frame = self.cap1.read() if ret and self.key != 0: img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) # 转换颜色使播放时保持原有色彩 current_image = Image.fromarray(img).resize((512, 384)) # 将图像转换成Image对象 imgtk = ImageTk.PhotoImage(image=current_image) self.lmain.imgtk = imgtk self.lmain.config(image=imgtk) self.lmain.update() # 刷线界面达到播放效果 cv2.waitKey(int(self.wait_time)) # 利用等待实现固定帧 else: break

将读取视频的代码改为读取播放图片,需要修改以下几个地方: 1. 将cv2.VideoCapture()改为使用PIL库中的Image.open()方法打开图片文件。 2. 在while循环中,不再使用cap1.read()方法读取视频帧,而是使用PIL库中的Image.open()方法打开图片文件。 3. 不再需要将读取的帧转换为RGBA格式,也不需要将其转换为Image对象。 4. 直接将读取的图片文件转换为ImageTk.PhotoImage对象,然后更新界面显示即可。 修改后的代码如下所示: ``` from PIL import Image, ImageTk def confirm_action(self): self.image_file = self.addressentry.get() # 图片文件路径 self.key = 1 self.image_play() # 图片文件播放 def image_play(self): self.wait_time = 1000 / 60 # 设置帧率 这里设置的是60帧 try: current_image = Image.open(self.image_file).resize((512, 384)) # 打开图片文件并转换为Image对象 imgtk = ImageTk.PhotoImage(image=current_image) # 将Image对象转换为ImageTk.PhotoImage对象 self.lmain.imgtk = imgtk self.lmain.config(image=imgtk) self.lmain.update() # 刷新界面显示 cv2.waitKey(int(self.wait_time)) # 利用等待实现固定帧 except: pass ``` 注意,这里假设您已经正确导入了PIL库和ImageTk模块。

相关推荐

import cv2 import sys import os import time from PyQt5 import QtGui #重新导入 from PyQt5 import QtCore #重新导入 from showPic import Ui_MainWindow from PyQt5.QtCore import * from PyQt5.QtGui import * #导入的外面 from PyQt5.QtWidgets import * camera_path = 0 # 0:自带摄像头 1:外接摄像头 "xxx.mp4" "rtsp://admin:pwd@192.168.2.10/cam/..." capture = cv2.VideoCapture(camera_path) # 初始化播放器 流媒体 fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V') # XVID/DIVX MPEG MJPG X264 video_writer = cv2.VideoWriter("image/myself.mp4", fourcc, 25, (960, 540)) # 存放路径、、帧率fps、尺寸(且保证下面的frame也是这个尺寸) class videoShow(QMainWindow, Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) self.dir_path = r"E:\pycharm\new_subject\image/" self.pushButton_play.clicked.connect(self.play_video) self.pushButton_pause.clicked.connect(self.pause_video) def play_video(self): self.playing = True def pause_video(self): self.playing = False def timer_pic(self): image_name = self.dir_path + self.file_list[self.n] url = image_name pic_image = cv2.imread(url) pic_image = cv2.cvtColor(pic_image, cv2.COLOR_BGR2RGB) # 将BGR格式图像转换成RGB height, width = pic_image.shape[:2] pixMap = QImage(pic_image.data, width, height, width*3, QImage.Format_RGB888) # 将RGB格式图像转换为八位图 pixMap = QPixmap.fromImage(pixMap) ratio = max(width/self.label.width(), height/self.label.height()) pixMap.setDevicePixelRatio(ratio) # 根据图片比例显示 self.label.setAlignment(Qt.AlignCenter) # 设置居中 self.label.setPixmap(pixMap) if self.playing: flag, frame = capture.read() if flag is False: return frame = cv2.resize(frame, (960, 540)) video_writer.write(frame) cv2.namedWindow("video", 0) cv2.imshow("video", frame) key = cv2.waitKey(25) if key == 27: video_writer.release() cv2.destroyAllWindows() sys.exit(0) if __name__ == '__main__': app = QApplication(sys.argv) ui = videoShow() ui.show() sys.exit(app.exec_()) 优化这段代码,实现录制视频以及点击按钮实现录制、播放、暂停

逐行详细解释以下代码并加注释from tensorflow import keras import matplotlib.pyplot as plt base_image_path = keras.utils.get_file( "coast.jpg", origin="https://img-datasets.s3.amazonaws.com/coast.jpg") plt.axis("off") plt.imshow(keras.utils.load_img(base_image_path)) #instantiating a model from tensorflow.keras.applications import inception_v3 model = inception_v3.InceptionV3(weights='imagenet',include_top=False) #配置各层对DeepDream损失的贡献 layer_settings = { "mixed4": 1.0, "mixed5": 1.5, "mixed6": 2.0, "mixed7": 2.5, } outputs_dict = dict( [ (layer.name, layer.output) for layer in [model.get_layer(name) for name in layer_settings.keys()] ] ) feature_extractor = keras.Model(inputs=model.inputs, outputs=outputs_dict) #定义损失函数 import tensorflow as tf def compute_loss(input_image): features = feature_extractor(input_image) loss = tf.zeros(shape=()) for name in features.keys(): coeff = layer_settings[name] activation = features[name] loss += coeff * tf.reduce_mean(tf.square(activation[:, 2:-2, 2:-2, :])) return loss #梯度上升过程 @tf.function def gradient_ascent_step(image, learning_rate): with tf.GradientTape() as tape: tape.watch(image) loss = compute_loss(image) grads = tape.gradient(loss, image) grads = tf.math.l2_normalize(grads) image += learning_rate * grads return loss, image def gradient_ascent_loop(image, iterations, learning_rate, max_loss=None): for i in range(iterations): loss, image = gradient_ascent_step(image, learning_rate) if max_loss is not None and loss > max_loss: break print(f"... Loss value at step {i}: {loss:.2f}") return image #hyperparameters step = 20. num_octave = 3 octave_scale = 1.4 iterations = 30 max_loss = 15. #图像处理方面 import numpy as np def preprocess_image(image_path): img = keras.utils.load_img(image_path) img = keras.utils.img_to_array(img) img = np.expand_dims(img, axis=0) img = keras.applications.inception_v3.preprocess_input(img) return img def deprocess_image(img): img = img.reshape((img.shape[1], img.shape[2], 3)) img /= 2.0 img += 0.5 img *= 255. img = np.clip(img, 0, 255).astype("uint8") return img #在多个连续 上运行梯度上升 original_img = preprocess_image(base_image_path) original_shape = original_img.shape[1:3] successive_shapes = [original_shape] for i in range(1, num_octave): shape = tuple([int(dim / (octave_scale ** i)) for dim in original_shape]) successive_shapes.append(shape) successive_shapes = successive_shapes[::-1] shrunk_original_img = tf.image.resize(original_img, successive_shapes[0]) img = tf.identity(original_img) for i, shape in enumerate(successive_shapes): print(f"Processing octave {i} with shape {shape}") img = tf.image.resize(img, shape) img = gradient_ascent_loop( img, iterations=iterations, learning_rate=step, max_loss=max_loss ) upscaled_shrunk_original_img = tf.image.resize(shrunk_original_img, shape) same_size_original = tf.image.resize(original_img, shape) lost_detail = same_size_original - upscaled_shrunk_original_img img += lost_detail shrunk_original_img = tf.image.resize(original_img, shape) keras.utils.save_img("DeepDream.png", deprocess_image(img.numpy()))

最新推荐

recommend-type

新建文本文档.txt

新建文本文档
recommend-type

开源Git gui工具Fork

开源Git gui工具Fork,CSDN能找到教程,但是资料不多,推荐用Tortoise
recommend-type

yolov5在华为昇腾atlas上加速推理

该资源为yolov5在华为昇腾atlas上使用Ascend310芯片加速推理,属于c++后端开发,适合C++开发者在华为昇腾盒子上移植深度学习算法的博主们。 资源是demo形式,包含完整的一套代码,还有转好的离线模型文件和跑出的测试结果图片。
recommend-type

C++ 实现贪吃蛇小游戏

C++贪吃蛇小游戏简介 内容概要 C++贪吃蛇小游戏是一款经典的2D游戏,它利用C++编程语言结合基本的图形库(如NCurses库或SDL库)实现。游戏的核心玩法包括控制贪吃蛇在封闭的场地内移动,通过吃掉随机出现的食物来增长身体长度,同时避免碰到场地边界或自己的身体,否则游戏结束。游戏界面简洁直观,通过键盘控制贪吃蛇的方向,提供流畅的游戏体验。 适用人群 C++贪吃蛇小游戏适用于广泛的人群,特别是: C++编程学习者:对于正在学习C++编程的学生或爱好者,这款小游戏是一个很好的实践项目。通过实现游戏,可以加深对C++语法、数据结构、面向对象编程等知识点的理解和应用。 使用场景及目标 C++贪吃蛇小游戏可以在以下场景中使用,并达到以下目标: 编程教学实践:在编程教学课堂上,教师可以使用该游戏作为案例,引导学生完成项目的开发。通过实践,学生可以更好地掌握C++编程技能,并将理论知识应用于实际项目中。 个人项目实践:对于个人学习者,实现贪吃蛇小游戏可以作为自我挑战和实践的机会。通过独立完成项目,可以提升自己的编程能力和解决问题的能力。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
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/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

HSV转为RGB的计算公式

HSV (Hue, Saturation, Value) 和 RGB (Red, Green, Blue) 是两种表示颜色的方式。下面是将 HSV 转换为 RGB 的计算公式: 1. 将 HSV 中的 S 和 V 值除以 100,得到范围在 0~1 之间的值。 2. 计算色相 H 在 RGB 中的值。如果 H 的范围在 0~60 或者 300~360 之间,则 R = V,G = (H/60)×V,B = 0。如果 H 的范围在 60~120 之间,则 R = ((120-H)/60)×V,G = V,B = 0。如果 H 的范围在 120~180 之间,则 R = 0,G = V,B =
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
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。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依