use html to show local flv file

本文介绍了一种在HTML页面中集成FLV播放器的方法,通过使用Flash对象和参数设置,实现了FLV文件的在线播放功能。

I have some .flv file download , and I create a file to show this files, seen that my computer has no flv displayer .

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CSS</title>
</head>
<body>


<h2>FlvPlayer</h2>

<center>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
	codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"
	height="800" width="1000">
	<param name="movie"
	
		value="vedio/flvPlayer.swf?vcastr_file=file:///C:/Documents%20and%20Settings/##/Desktop/css_train/vedio/12.flv">
	<param name="quality" value="high">
	<embed
		src="vedio/flvPlayer.swf?vcastr_file=file:///C:/Documents%20and%20Settings/##/Desktop/css_train/vedio/12.flv"
		quality="high" 
		pluginspage="http://www.macromedia.com/go/getflashplayer"
		type="application/x-shockwave-flash" width="1000" height="800">
	</embed>
</object>
</center>
</body>
</html>
import os import sys import json import shutil import threading import winreg import ctypes from PIL import Image, ImageTk import tkinter as tk from tkinter import ttk, messagebox, filedialog from ctypes import wintypes # 启用Windows 10/11的亚克力效果 if sys.platform == 'win32': try: DWMWA_USE_IMMERSIVE_DARK_MODE = 20 DWMWA_WINDOW_CORNER_PREFERENCE = 33 DWMWA_SYSTEMBACKDROP_TYPE = 38 # Windows 11的背景效果类型 class BackdropType: DWMSBT_DISABLE = 1 # 无特效 DWMSBT_MAINWINDOW = 2 # 云母效果 DWMSBT_TRANSIENTWINDOW = 3 # 亚克力效果 DWMSBT_TABBEDWINDOW = 4 # 标签页效果 # 设置窗口特效 def set_window_effect(hwnd, effect_type): if not hasattr(ctypes, "windll"): return try: dwm = ctypes.windll.dwmapi value = ctypes.c_int(effect_type) dwm.DwmSetWindowAttribute( wintypes.HWND(hwnd), DWMWA_SYSTEMBACKDROP_TYPE, ctypes.byref(value), ctypes.sizeof(value) ) except Exception as e: print(f"设置窗口特效失败: {e}") # 设置深色模式 def set_dark_mode(hwnd): if not hasattr(ctypes, "windll"): return try: dwm = ctypes.windll.dwmapi value = ctypes.c_int(1) # 深色模式 dwm.DwmSetWindowAttribute( wintypes.HWND(hwnd), DWMWA_USE_IMMERSIVE_DARK_MODE, ctypes.byref(value), ctypes.sizeof(value) ) except Exception as e: print(f"设置深色模式失败: {e}") except Exception as e: print(f"初始化Windows特效失败: {e}") class DesktopGrid: """表示桌面上的一个整理格子""" def __init__(self, canvas, x, y, size, color, index, target_dir): self.canvas = canvas self.x = x self.y = y self.size = size self.color = color self.index = index self.target_dir = target_dir self.files = [] self.selected = False self.drag_start = None self.hovered = False # 创建圆角矩形 self.rect = self.create_rounded_rectangle( x, y, x+size, y+size, radius=15, fill=color, outline="#FFFFFF", width=1, alpha=180 # 70% 透明度 ) # 创建标签 self.label = canvas.create_text( x + size/2, y + size/2, text=f"格子 {index}", fill="white", font=("Segoe UI", 11, "bold"), anchor=tk.CENTER ) # 绑定事件 self.canvas.tag_bind(self.rect, "<ButtonPress-1>", self.on_press) self.canvas.tag_bind(self.rect, "<B1-Motion>", self.on_drag) self.canvas.tag_bind(self.rect, "<ButtonRelease-1>", self.on_release) self.canvas.tag_bind(self.rect, "<Enter>", self.on_enter) self.canvas.tag_bind(self.rect, "<Leave>", self.on_leave) # 确保目标目录存在 os.makedirs(target_dir, exist_ok=True) def create_rounded_rectangle(self, x1, y1, x2, y2, radius=25, **kwargs): """创建圆角矩形(支持半透明)""" # 创建透明图像作为纹理 alpha = kwargs.pop('alpha', 255) fill = kwargs.pop('fill', '#FFFFFF') # 创建圆角矩形图像 image = Image.new('RGBA', (self.size, self.size), (0, 0, 0, 0)) pixels = image.load() # 计算圆角 for y in range(self.size): for x in range(self.size): # 检查是否在圆角范围内 dist_x = min(x, self.size - x - 1) dist_y = min(y, self.size - y - 1) # 计算到最近角的距离 if dist_x < radius and dist_y < radius: dist = ((radius - dist_x) ** 2 + (radius - dist_y) ** 2) ** 0.5 if dist > radius: continue # 设置像素颜色(带透明度) r, g, b = int(fill[1:3], 16), int(fill[3:5], 16), int(fill[5:7], 16) pixels[x, y] = (r, g, b, alpha) # 转换为Tkinter图像 self.tk_image = ImageTk.PhotoImage(image) return self.canvas.create_image( x1 + self.size/2, y1 + self.size/2, image=self.tk_image, tags="grid" ) def on_press(self, event): """鼠标按下事件""" self.drag_start = (event.x, event.y) self.selected = True self.canvas.tag_raise(self.rect) self.canvas.tag_raise(self.label) self.update_appearance() def on_drag(self, event): """拖动事件""" if self.drag_start: dx = event.x - self.drag_start[0] dy = event.y - self.drag_start[1] self.canvas.move(self.rect, dx, dy) self.canvas.move(self.label, dx, dy) self.x += dx self.y += dy self.drag_start = (event.x, event.y) # 检查是否需要吸附到其他格子 self.check_snap() def check_snap(self): """检查并执行吸附到其他格子""" snap_threshold = 20 # 吸附阈值 for grid in self.canvas.grids: if grid != self: # 水平吸附 if abs(self.x - grid.x) < snap_threshold: self.x = grid.x # 垂直吸附 if abs(self.y - grid.y) < snap_threshold: self.y = grid.y # 更新位置 self.canvas.coords(self.rect, self.x, self.y) self.canvas.coords(self.label, self.x + self.size/2, self.y + self.size/2) def on_release(self, event): """鼠标释放事件""" self.drag_start = None self.update_appearance() def on_enter(self, event): """鼠标进入事件""" self.hovered = True self.update_appearance() def on_leave(self, event): """鼠标离开事件""" self.hovered = False self.update_appearance() def update_appearance(self): """更新格子的外观(悬停/选中状态)""" if self.selected: # 选中状态 - 更亮的颜色 self.canvas.itemconfig( self.rect, image=self.create_highlighted_image(self.color, 220) ) elif self.hovered: # 悬停状态 - 稍亮的颜色 self.canvas.itemconfig( self.rect, image=self.create_highlighted_image(self.color, 200) ) else: # 正常状态 self.canvas.itemconfig( self.rect, image=self.create_normal_image(self.color) ) def create_normal_image(self, color): """创建正常状态的图像""" return self.create_rounded_rectangle( self.x, self.y, self.x+self.size, self.y+self.size, radius=15, fill=color, alpha=180 ) def create_highlighted_image(self, color, alpha): """创建高亮状态的图像""" # 计算高亮颜色(增加亮度) r = min(255, int(int(color[1:3], 16) * 1.2)) g = min(255, int(int(color[3:5], 16) * 1.2)) b = min(255, int(int(color[5:7], 16) * 1.2)) new_color = f"#{r:02x}{g:02x}{b:02x}" return self.create_rounded_rectangle( self.x, self.y, self.x+self.size, self.y+self.size, radius=15, fill=new_color, alpha=alpha ) def add_file(self, file_path): """添加文件到格子""" try: # 移动文件到目标目录 filename = os.path.basename(file_path) dest_path = os.path.join(self.target_dir, filename) # 避免覆盖同名文件 counter = 1 base_name, ext = os.path.splitext(filename) while os.path.exists(dest_path): new_filename = f"{base_name}_{counter}{ext}" dest_path = os.path.join(self.target_dir, new_filename) counter += 1 shutil.move(file_path, dest_path) self.files.append(dest_path) # 更新标签显示文件名 display_name = filename if len(filename) < 15 else filename[:12] + "..." self.canvas.itemconfig( self.label, text=f"格子 {self.index}\n{display_name}" ) return True except Exception as e: messagebox.showerror("错误", f"添加文件失败: {str(e)}") return False class DesktopOrganizerApp: def __init__(self, root): self.root = root self.root.title("高级桌面整理工具") self.root.geometry("1000x700+200+100") # 设置深色背景作为基础 self.root.configure(bg='#2B2B2B') # 设置Windows特效 if sys.platform == 'win32': try: # 获取窗口句柄 hwnd = ctypes.windll.user32.GetParent(root.winfo_id()) # 设置深色模式 set_dark_mode(hwnd) # 设置云母效果 set_window_effect(hwnd, BackdropType.DWMSBT_MAINWINDOW) except Exception as e: print(f"设置Windows特效失败: {e}") # 回退方案:设置半透明背景 self.root.attributes('-alpha', 0.95) # 修复:使用有效的背景色 self.canvas = tk.Canvas( root, bg='#2B2B2B', # 使用深灰色背景 highlightthickness=0 ) self.canvas.pack(fill=tk.BOTH, expand=True) self.canvas.grids = [] # 存储所有格子 # 初始格子布局 self.grid_colors = [ '#FF6B6B', '#4ECDC4', '#FFE66D', '#1A535C', '#FF9F1C' ] # 创建初始格子 self.create_initial_grids() # 右键菜单 self.context_menu = tk.Menu(root, tearoff=0, bg='#3C3C3C', fg='white') self.context_menu.add_command( label="添加新格子", command=self.add_new_grid, background='#3C3C3C', foreground='white' ) self.context_menu.add_command( label="删除选中格子", command=self.delete_selected_grid, background='#3C3C3C', foreground='white' ) self.context_menu.add_command( label="添加文件", command=self.add_files_to_grid, background='#3C3C3C', foreground='white' ) self.context_menu.add_separator() self.context_menu.add_command( label="保存布局", command=self.save_layout, background='#3C3C3C', foreground='white' ) self.context_menu.add_command( label="加载布局", command=self.load_layout, background='#3C3C3C', foreground='white' ) self.context_menu.add_separator() self.context_menu.add_command( label="退出", command=root.destroy, background='#3C3C3C', foreground='white' ) # 绑定事件 self.root.bind("<Button-3>", self.show_context_menu) self.root.bind("<Control-n>", lambda e: self.add_new_grid()) self.root.bind("<Delete>", lambda e: self.delete_selected_grid()) self.root.bind("<Control-s>", lambda e: self.save_layout()) self.root.bind("<Control-o>", lambda e: self.load_layout()) # 状态栏 self.status_var = tk.StringVar() self.status_var.set("就绪 | 右键菜单添加文件或格子") status_bar = ttk.Label( root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W, background='#333333', foreground='white' ) status_bar.pack(side=tk.BOTTOM, fill=tk.X) # 文件监视器 self.start_file_monitor() def create_initial_grids(self): """创建初始格子布局""" grid_size = 220 positions = [ (50, 50), # 左上 (300, 50), # 右上 (50, 300), # 左下 (300, 300), # 右下 (550, 180) # 中间 ] for i, (x, y) in enumerate(positions): color = self.grid_colors[i % len(self.grid_colors)] target_dir = os.path.expanduser(f"~/Desktop/整理格子_{i+1}") grid = DesktopGrid( self.canvas, x, y, grid_size, color, i+1, target_dir ) self.canvas.grids.append(grid) def add_new_grid(self): """添加新格子""" color = self.grid_colors[len(self.canvas.grids) % len(self.grid_colors)] target_dir = os.path.expanduser(f"~/Desktop/整理格子_{len(self.canvas.grids)+1}") grid = DesktopGrid( self.canvas, 400, 300, 220, color, len(self.canvas.grids)+1, target_dir ) self.canvas.grids.append(grid) self.status_var.set(f"已添加新格子: {len(self.canvas.grids)}") def delete_selected_grid(self): """删除选中的格子""" for grid in self.canvas.grids[:]: if grid.selected: self.canvas.delete(grid.rect) self.canvas.delete(grid.label) self.canvas.grids.remove(grid) self.status_var.set("已删除选中的格子") return self.status_var.set("没有选中的格子") def save_layout(self): """保存布局到文件""" try: layout_data = [] for grid in self.canvas.grids: layout_data.append({ "x": grid.x, "y": grid.y, "size": grid.size, "color": grid.color, "index": grid.index, "target_dir": grid.target_dir }) # 保存到用户文档目录 save_path = os.path.expanduser("~/Documents/desktop_grid_layout.json") with open(save_path, "w") as f: json.dump(layout_data, f, indent=4) self.status_var.set(f"布局已保存到: {save_path}") messagebox.showinfo("成功", f"布局已保存到: {save_path}") except Exception as e: messagebox.showerror("错误", f"保存失败: {str(e)}") def load_layout(self): """从文件加载布局""" try: load_path = os.path.expanduser("~/Documents/desktop_grid_layout.json") if not os.path.exists(load_path): messagebox.showerror("错误", f"找不到布局文件: {load_path}") return with open(load_path, "r") as f: layout_data = json.load(f) # 清除现有格子 for grid in self.canvas.grids[:]: self.canvas.delete(grid.rect) self.canvas.delete(grid.label) self.canvas.grids = [] # 创建新格子 for data in layout_data: grid = DesktopGrid( self.canvas, data["x"], data["y"], data["size"], data["color"], data["index"], data["target_dir"] ) self.canvas.grids.append(grid) self.status_var.set(f"已加载布局: {load_path}") messagebox.showinfo("成功", f"已从 {load_path} 加载布局") except Exception as e: messagebox.showerror("错误", f"加载布局失败: {str(e)}") def add_files_to_grid(self): """添加文件到选中的格子""" selected_grid = None for grid in self.canvas.grids: if grid.selected: selected_grid = grid break if not selected_grid: messagebox.showwarning("警告", "请先选择一个格子") return file_paths = filedialog.askopenfilenames( title="选择要添加的文件", filetypes=[("所有文件", "*.*")] ) if not file_paths: return for file_path in file_paths: if selected_grid.add_file(file_path): self.status_var.set(f"已添加: {os.path.basename(file_path)} -> 格子 {selected_grid.index}") def show_context_menu(self, event): """显示右键菜单""" self.context_menu.post(event.x_root, event.y_root) def start_file_monitor(self): """启动文件监视器(监视桌面文件夹)""" # 获取桌面路径 desktop_path = os.path.expanduser("~/Desktop") # 使用线程监视桌面文件夹 threading.Thread( target=self.monitor_desktop, args=(desktop_path,), daemon=True ).start() self.status_var.set("已启动桌面文件监视器...") def monitor_desktop(self, path): """监视桌面文件夹并自动整理新文件""" import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class DesktopHandler(FileSystemEventHandler): def __init__(self, app): self.app = app self.last_handled = set() self.last_event_time = 0 def on_created(self, event): # 只处理文件(跳过目录) if not event.is_directory: current_time = time.time() # 防止短时间内重复触发 if current_time - self.last_event_time < 0.5: return self.last_event_time = current_time file_path = event.src_path # 延迟处理,确保文件已完全写入 time.sleep(0.5) # 避免重复处理 if file_path not in self.last_handled: self.last_handled.add(file_path) # 在新线程中整理文件 threading.Thread( target=self.app.auto_organize_file, args=(file_path,), daemon=True ).start() event_handler = DesktopHandler(self) observer = Observer() observer.schedule(event_handler, path, recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() def auto_organize_file(self, file_path): """自动整理文件到合适的格子""" # 确保文件存在 if not os.path.exists(file_path) or os.path.isdir(file_path): return # 获取文件扩展名 _, ext = os.path.splitext(file_path) ext = ext.lower() # 根据文件类型选择格子 category = self.classify_file(ext) # 查找对应类别的格子 target_grid = None for grid in self.canvas.grids: grid_category = self.classify_grid(grid) if grid_category == category: target_grid = grid break # 如果没有找到匹配的格子,使用第一个格子 if not target_grid and self.canvas.grids: target_grid = self.canvas.grids[0] # 添加文件 if target_grid: if target_grid.add_file(file_path): self.status_var.set(f"自动整理: {os.path.basename(file_path)} -> {target_grid.target_dir}") def classify_file(self, ext): """根据文件扩展名分类文件""" categories = { 'documents': ['.pdf', '.doc', '.docx', '.txt', '.xls', '.xlsx', '.ppt', '.pptx', '.rtf'], 'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.tiff'], 'videos': ['.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.mpeg'], 'music': ['.mp3', '.wav', '.flac', '.aac', '.ogg', '.m4a'], 'archives': ['.zip', '.rar', '.7z', '.tar', '.gz', '.bz2'], 'executables': ['.exe', '.msi', '.bat', '.sh'], 'code': ['.py', '.js', '.html', '.css', '.java', '.cpp', '.cs', '.php'] } for cat, exts in categories.items(): if ext in exts: return cat return 'others' def classify_grid(self, grid): """根据格子中的文件类型确定格子类别""" if not grid.files: return 'others' # 统计格子中文件类型的分布 type_count = {} for file_path in grid.files: _, ext = os.path.splitext(file_path) ext = ext.lower() cat = self.classify_file(ext) type_count[cat] = type_count.get(cat, 0) + 1 # 返回最常见的类型 return max(type_count, key=type_count.get) # 创建主窗口 if __name__ == "__main__": root = tk.Tk() app = DesktopOrganizerApp(root) # 设置任务栏图标 if sys.platform == 'win32': try: base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) icon_path = os.path.join(base_path, "app_icon.ico") root.iconbitmap(icon_path) except: try: # 尝试从当前目录加载 root.iconbitmap("app_icon.ico") except: print("图标文件加载失败,使用默认图标") # 启动主循环 root.mainloop() [Running] python -u "e:\system\Desktop\项目所需文件\工具\桌面整理工具\Desktop Grid Organizer.py" Traceback (most recent call last): File "e:\system\Desktop\\u9879�ڏ�������\�H��\\u684c�ʐ����H��\Desktop Grid Organizer.py", line 639, in <module> root.iconbitmap(icon_path) File "C:\Users\cheny9210\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 2156, in wm_iconbitmap return self.tk.call('wm', 'iconbitmap', self._w, bitmap) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ _tkinter.TclError: bitmap "e:\system\Desktop\\u9879�ڏ�������\�H��\\u684c�ʐ����H��\app_icon.ico" not defined During handling of the above exception, another exception occurred: Traceback (most recent call last): File "e:\system\Desktop\\u9879�ڏ�������\�H��\\u684c�ʐ����H��\Desktop Grid Organizer.py", line 643, in <module> root.iconbitmap("app_icon.ico") File "C:\Users\cheny9210\AppData\Local\Programs\Python\Python312\Lib\tkinter\__init__.py", line 2156, in wm_iconbitmap return self.tk.call('wm', 'iconbitmap', self._w, bitmap) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ _tkinter.TclError: bitmap "app_icon.ico" not defined During handling of the above exception, another exception occurred: Traceback (most recent call last): File "e:\system\Desktop\\u9879�ڏ�������\�H��\\u684c�ʐ����H��\Desktop Grid Organizer.py", line 645, in <module> print("\u56fe\u6807������\u8f7d��\u8d25�C�g�p��\u8ba4\u56fe\u6807") UnicodeEncodeError: 'cp932' codec can't encode character '\u56fe' in position 0: illegal multibyte sequence [Done] exited with code=1 in 0.766 seconds
最新发布
10-18
[admin@Liliang-01 ~]$ schematool -initSchema -dbType mysql declare -x CLASSPATH=".:/home/admin/java/jdk1.8.0_131/lib/tools.jar:/home/admin/java/jdk1.8.0_131/lib/dt.jar" declare -x HADOOP_HEAPSIZE="256" declare -x HADOOP_HOME="/home/admin/hadoop/hadoop-2.7.3" declare -x HBASE_HOME="/home/admin/hbase/hbase-1.2.3" declare -x HISTCONTROL="ignoredups" declare -x HISTSIZE="1000" declare -x HIVE_AUX_JARS_PATH="" declare -x HIVE_CONF_DIR="/home/admin/hive/apache-hive-2.1.1-bin/conf" declare -x HIVE_HOME="/home/admin/hive/apache-hive-2.1.1-bin" declare -x HOME="/home/admin" declare -x HOSTNAME="Liliang-01" declare -x JAVA_HOME="/home/admin/java/jdk1.8.0_131" declare -x LANG="zh_CN.UTF-8" declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s" declare -x LOGNAME="admin" declare -x LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:" declare -x MAIL="/var/spool/mail/admin" declare -x MYSQL_CLUSTER_HOME="/usr/local/mysql" declare -x OLDPWD declare -x PATH="/home/admin/hive/apache-hive-2.1.1-bin/bin:/home/admin/hbase/hbase-1.2.3/bin:/home/admin/hadoop/hadoop-2.7.3/bin:/home/admin/hadoop/hadoop-2.7.3/sbin:/home/admin/zookeeper/zookeeper-3.4.9/bin:/home/admin/java/jdk1.8.0_131/bin:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/admin/.local/bin:/home/admin/bin" declare -x PWD="/home/admin" declare -x SHELL="/bin/bash" declare -x SHLVL="4" declare -x SSH_CLIENT="192.168.100.2 57416 22" declare -x SSH_CONNECTION="192.168.100.2 57416 192.168.100.10 22" declare -x SSH_TTY="/dev/pts/2" declare -x TERM="xterm" declare -x USER="admin" declare -x XDG_RUNTIME_DIR="/run/user/1000" declare -x XDG_SESSION_ID="48" declare -x ZOOKEEPER_HOME="/home/admin/zookeeper/zookeeper-3.4.9" declare -x CLASSPATH=".:/home/admin/java/jdk1.8.0_131/lib/tools.jar:/home/admin/java/jdk1.8.0_131/lib/dt.jar" declare -x HADOOP_HEAPSIZE="256" declare -x HADOOP_HOME="/home/admin/hadoop/hadoop-2.7.3" declare -x HBASE_HOME="/home/admin/hbase/hbase-1.2.3" declare -x HISTCONTROL="ignoredups" declare -x HISTSIZE="1000" declare -x HIVE_AUX_JARS_PATH="" declare -x HIVE_CONF_DIR="/home/admin/hive/apache-hive-2.1.1-bin/conf" declare -x HIVE_HOME="/home/admin/hive/apache-hive-2.1.1-bin" declare -x HOME="/home/admin" declare -x HOSTNAME="Liliang-01" declare -x JAVA_HOME="/home/admin/java/jdk1.8.0_131" declare -x LANG="zh_CN.UTF-8" declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s" declare -x LOGNAME="admin" declare -x LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:" declare -x MAIL="/var/spool/mail/admin" declare -x MYSQL_CLUSTER_HOME="/usr/local/mysql" declare -x OLDPWD declare -x PATH="/home/admin/hive/apache-hive-2.1.1-bin/bin:/home/admin/hbase/hbase-1.2.3/bin:/home/admin/hadoop/hadoop-2.7.3/bin:/home/admin/hadoop/hadoop-2.7.3/sbin:/home/admin/zookeeper/zookeeper-3.4.9/bin:/home/admin/java/jdk1.8.0_131/bin:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/admin/.local/bin:/home/admin/bin" declare -x PWD="/home/admin" declare -x SHELL="/bin/bash" declare -x SHLVL="4" declare -x SSH_CLIENT="192.168.100.2 57416 22" declare -x SSH_CONNECTION="192.168.100.2 57416 192.168.100.10 22" declare -x SSH_TTY="/dev/pts/2" declare -x TERM="xterm" declare -x USER="admin" declare -x XDG_RUNTIME_DIR="/run/user/1000" declare -x XDG_SESSION_ID="48" declare -x ZOOKEEPER_HOME="/home/admin/zookeeper/zookeeper-3.4.9" SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/home/admin/hive/apache-hive-2.1.1-bin/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/home/admin/hadoop/hadoop-2.7.3/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory] Metastore connection URL: jdbc:mysql://Liliang-04:3306/hive?createDatabaseIfNotExist=true&characterEncoding=UTF-8&useSSL=false Metastore Connection Driver : com.mysql.jdbc.Driver Metastore connection User: hive org.apache.hadoop.hive.metastore.HiveMetaException: Failed to get schema version. Underlying cause: java.sql.SQLException : Access denied for user 'hive'@'Liliang-01' (using password: YES) SQL Error code: 1045 Use --verbose for detailed stacktrace. *** schemaTool failed *** [admin@Liliang-01 ~]$ vi ~/hive/apache-hive-2.1.1-bin/conf/hive-site.xml [admin@Liliang-01 ~]$ schematool -initSchema -dbType mysql declare -x CLASSPATH=".:/home/admin/java/jdk1.8.0_131/lib/tools.jar:/home/admin/java/jdk1.8.0_131/lib/dt.jar" declare -x HADOOP_HEAPSIZE="256" declare -x HADOOP_HOME="/home/admin/hadoop/hadoop-2.7.3" declare -x HBASE_HOME="/home/admin/hbase/hbase-1.2.3" declare -x HISTCONTROL="ignoredups" declare -x HISTSIZE="1000" declare -x HIVE_AUX_JARS_PATH="" declare -x HIVE_CONF_DIR="/home/admin/hive/apache-hive-2.1.1-bin/conf" declare -x HIVE_HOME="/home/admin/hive/apache-hive-2.1.1-bin" declare -x HOME="/home/admin" declare -x HOSTNAME="Liliang-01" declare -x JAVA_HOME="/home/admin/java/jdk1.8.0_131" declare -x LANG="zh_CN.UTF-8" declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s" declare -x LOGNAME="admin" declare -x LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:" declare -x MAIL="/var/spool/mail/admin" declare -x MYSQL_CLUSTER_HOME="/usr/local/mysql" declare -x OLDPWD declare -x PATH="/home/admin/hive/apache-hive-2.1.1-bin/bin:/home/admin/hbase/hbase-1.2.3/bin:/home/admin/hadoop/hadoop-2.7.3/bin:/home/admin/hadoop/hadoop-2.7.3/sbin:/home/admin/zookeeper/zookeeper-3.4.9/bin:/home/admin/java/jdk1.8.0_131/bin:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/admin/.local/bin:/home/admin/bin" declare -x PWD="/home/admin" declare -x SHELL="/bin/bash" declare -x SHLVL="4" declare -x SSH_CLIENT="192.168.100.2 57416 22" declare -x SSH_CONNECTION="192.168.100.2 57416 192.168.100.10 22" declare -x SSH_TTY="/dev/pts/2" declare -x TERM="xterm" declare -x USER="admin" declare -x XDG_RUNTIME_DIR="/run/user/1000" declare -x XDG_SESSION_ID="48" declare -x ZOOKEEPER_HOME="/home/admin/zookeeper/zookeeper-3.4.9" declare -x CLASSPATH=".:/home/admin/java/jdk1.8.0_131/lib/tools.jar:/home/admin/java/jdk1.8.0_131/lib/dt.jar" declare -x HADOOP_HEAPSIZE="256" declare -x HADOOP_HOME="/home/admin/hadoop/hadoop-2.7.3" declare -x HBASE_HOME="/home/admin/hbase/hbase-1.2.3" declare -x HISTCONTROL="ignoredups" declare -x HISTSIZE="1000" declare -x HIVE_AUX_JARS_PATH="" declare -x HIVE_CONF_DIR="/home/admin/hive/apache-hive-2.1.1-bin/conf" declare -x HIVE_HOME="/home/admin/hive/apache-hive-2.1.1-bin" declare -x HOME="/home/admin" declare -x HOSTNAME="Liliang-01" declare -x JAVA_HOME="/home/admin/java/jdk1.8.0_131" declare -x LANG="zh_CN.UTF-8" declare -x LESSOPEN="||/usr/bin/lesspipe.sh %s" declare -x LOGNAME="admin" declare -x LS_COLORS="rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:" declare -x MAIL="/var/spool/mail/admin" declare -x MYSQL_CLUSTER_HOME="/usr/local/mysql" declare -x OLDPWD declare -x PATH="/home/admin/hive/apache-hive-2.1.1-bin/bin:/home/admin/hbase/hbase-1.2.3/bin:/home/admin/hadoop/hadoop-2.7.3/bin:/home/admin/hadoop/hadoop-2.7.3/sbin:/home/admin/zookeeper/zookeeper-3.4.9/bin:/home/admin/java/jdk1.8.0_131/bin:/usr/local/mysql/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/admin/.local/bin:/home/admin/bin" declare -x PWD="/home/admin" declare -x SHELL="/bin/bash" declare -x SHLVL="4" declare -x SSH_CLIENT="192.168.100.2 57416 22" declare -x SSH_CONNECTION="192.168.100.2 57416 192.168.100.10 22" declare -x SSH_TTY="/dev/pts/2" declare -x TERM="xterm" declare -x USER="admin" declare -x XDG_RUNTIME_DIR="/run/user/1000" declare -x XDG_SESSION_ID="48" declare -x ZOOKEEPER_HOME="/home/admin/zookeeper/zookeeper-3.4.9" SLF4J: Class path contains multiple SLF4J bindings. SLF4J: Found binding in [jar:file:/home/admin/hive/apache-hive-2.1.1-bin/lib/log4j-slf4j-impl-2.4.1.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: Found binding in [jar:file:/home/admin/hadoop/hadoop-2.7.3/share/hadoop/common/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class] SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory] Metastore connection URL: jdbc:mysql://Liliang-04:3306/hive?createDatabaseIfNotExist=true&characterEncoding=UTF-8&useSSL=false Metastore Connection Driver : com.mysql.jdbc.Driver Metastore connection User: hive org.apache.hadoop.hive.metastore.HiveMetaException: Failed to get schema version. Underlying cause: java.sql.SQLException : Access denied for user 'hive'@'Liliang-01' (using password: YES) SQL Error code: 1045 Use --verbose for detailed stacktrace. *** schemaTool failed *** 分析错误
06-11
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QMenu, QAction from ui.win import Ui_mainWindow from PyQt5.QtCore import Qt, QPoint, QTimer, QThread, pyqtSignal from PyQt5.QtGui import QImage, QPixmap, QPainter, QIcon import sys import os import json import numpy as np import torch import torch.backends.cudnn as cudnn import os import time import cv2 import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) from models.experimental import attempt_load from utils.datasets import LoadImages, LoadWebcam from utils.CustomMessageBox import MessageBox from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \ apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path # from utils.plots import colors, plot_one_box, plot_one_box_PIL from utils.plots import Annotator, colors, save_one_box from utils.torch_utils import select_device from utils.capnums import Camera from deep_sort.deep_sort import DeepSort def deepsort_update(Tracker, pred, xywh, np_img): outputs = Tracker.update(xywh, pred[:, 4:5], pred[:, 5].tolist(), cv2.cvtColor(np_img, cv2.COLOR_BGR2RGB)) return outputs class DetThread(QThread): send_img = pyqtSignal(np.ndarray) send_raw = pyqtSignal(np.ndarray) send_statistic = pyqtSignal(dict) send_msg = pyqtSignal(str) send_percent = pyqtSignal(int) send_fps = pyqtSignal(str) def __init__(self,tracker = 'ByteTrack',imgsz=(640,640)): super(DetThread, self).__init__() self.weights = './yolov5s.pt' self.current_weight = './yolov5s.pt' self.source = '0' self.conf_thres = 0.25 self.iou_thres = 0.45 self.jump_out = False # jump out of the loop self.is_continue = True # continue/pause self.percent_length = 1000 # progress bar self.rate_check = True # Whether to enable delay self.rate = 100 self.imgsz = check_img_size(imgsz) self.save_fold = './result' if tracker == 'DeepSort': self.tracker = DeepSort('deep_sort/deep_sort/deep/checkpoint/ckpt_car3.t7') self._type = 'DeepSort' @torch.no_grad() def run(self, imgsz=640, max_det=1000, # maximum detections per image device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu view_img=True, # show results save_txt=False, # save results to *.txt save_conf=False, # save confidences in --save-txt labels save_crop=False, # save cropped prediction boxes nosave=False, # do not save images/videos classes=None, # filter by class: --class 0, or --class 0 2 3 agnostic_nms=False, # class-agnostic NMS augment=False, # augmented inference visualize=False, # visualize features update=False, # update all models project='runs/detect', # save results to project/name name='exp', # save results to project/name exist_ok=False, # existing project/name ok, do not increment line_thickness=3, # bounding box thickness (pixels) hide_labels=False, # hide labels hide_conf=False, # hide confidences half=False, # use FP16 half-precision inference ): # 初始化 try: # 选择设备(如CPU或GPU) device = select_device(device) # 如果设备不是CPU,设置half为True以使用半精度浮点数 half &= device.type != 'cpu' # 尝试加载模型,并将模型加载到指定设备上 model = attempt_load(self.weights, map_location=device) num_params = 0 # 计算模型参数的总数 for param in model.parameters(): num_params += param.numel() # 获取模型的步幅(stride),并确保图像尺寸是步幅的倍数 stride = int(model.stride.max()) imgsz = check_img_size(imgsz, s=stride) # 获取模型的类别名称 names = model.module.names if hasattr(model, 'module') else model.names # 如果使用半精度浮点数,转换模型的权重为半精度 if half: model.half() # 如果使用CUDA设备,进行一次空推理以初始化模型 if device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) deepsort_tracker = DeepSort('deep_sort/deep_sort/deep/checkpoint/ckpt_car3.t7') # 数据加载 if self.source.isnumeric() or self.source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://')): view_img = check_imshow() cudnn.benchmark = True # set True to speed up constant image size inference dataset = LoadWebcam(self.source, img_size=imgsz, stride=stride) # bs = len(dataset) # batch_size else: dataset = LoadImages(self.source, img_size=imgsz, stride=stride) #根据输入源(视频流或本地图片/视频)加载数据。如果是视频流,启用 cudnn.benchmark 以加速推理 count = 0 jump_count = 0 start_time = time.time() dataset = iter(dataset) #主循环 while True: if self.jump_out: self.vid_cap.release() self.send_percent.emit(0) self.send_msg.emit('停止') if hasattr(self, 'out'): self.out.release() break #主循环处理每一帧数据。如果接收到跳出信号,则释放资源并退出循环 # 更换模型 # 如果当前权重与新权重不一致,更新模型 if self.current_weight != self.weights: # 加载模型 model = attempt_load(self.weights, map_location=device) # 加载FP32模型(32位浮点数) num_params = 0 # 计算模型参数总数 for param in model.parameters(): num_params += param.numel() # 获取模型步幅(stride) stride = int(model.stride.max()) # 检查图像尺寸是否为步幅的整数倍 imgsz = check_img_size(imgsz, s=stride) # 获取模型的类别名称 names = model.module.names if hasattr(model, 'module') else model.names # 如果使用半精度浮点数,转换模型权重为FP16(16位浮点数) if half: model.half() # 如果设备不是CPU,运行一次模型以完成初始化 if device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # 更新当前权重 self.current_weight = self.weights #如果检测到模型权重发生改变,重新加载模型。 #数据预处理 # 如果继续处理标志位为True,则执行以下代码 if self.is_continue: # 从数据集中获取下一帧数据,包括路径、图像、原始图像和视频捕获对象 path, img, im0s, self.vid_cap = next(dataset) count += 1 # 帧计数器加一 # 每处理30帧,计算一次FPS(帧率) if count % 30 == 0 and count >= 30: fps = int(30 / (time.time() - start_time)) # 计算30帧处理所需时间的平均FPS self.send_fps.emit('fps:' + str(fps)) # 发送FPS信号 start_time = time.time() # 重新记录开始时间 # 如果有视频捕获对象,计算视频处理进度百分比 if self.vid_cap: percent = int(count / self.vid_cap.get(cv2.CAP_PROP_FRAME_COUNT) * self.percent_length) self.send_percent.emit(percent) # 发送进度百分比信号 else: percent = self.percent_length # 如果没有视频捕获对象,设定进度为满 # 初始化统计字典,统计每个类别的数量 statistic_dic = {name: 0 for name in names} # 将图像从numpy数组转换为torch张量,并加载到指定设备(如GPU) img = torch.from_numpy(img).to(device) # 如果使用半精度浮点数,转换图像数据类型,否则转换为浮点数 img = img.half() if half else img.float() # uint8 to fp16/32 img /= 255.0 # 将像素值从0-255归一化到0.0-1.0 # 如果图像是三维的,增加一个维度以匹配模型输入要求 if img.ndimension() == 3: img = img.unsqueeze(0) # 推理 pred = model(img, augment=augment)[0] #NMS pred = non_max_suppression(pred, self.conf_thres, self.iou_thres, classes, agnostic_nms, max_det=max_det) # 处理检测结果 迭代每个检测结果,并绘制边界框和标签 # 遍历每张图像的检测结果 for i, det in enumerate(pred): # detections per image # 复制原始图像,以便在上面绘制标注 im0 = im0s.copy() # 创建一个Annotator对象,用于在图像上绘制标注 annotator = Annotator(im0, line_width=line_thickness, example=str(names)) # 如果有检测结果 if len(det): # 将检测框的坐标从img_size尺度重新缩放到原始图像尺度,并四舍五入 det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round() # 进行目标跟踪 track_outputs = deepsort_update(deepsort_tracker, det.cpu(), det[:, :4].cpu(), im0) # Write results # for *xyxy, conf, cls in reversed(det): # c = int(cls) # integer class # statistic_dic[names[c]] += 1 # label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') # annotator.box_label(xyxy, label, color=colors(c, True)) # 将跟踪结果绘制到图片上 if len(track_outputs)>0: for track_output in track_outputs: xyxy = track_output[:4] c = int(track_output[4]) # integer class track_id = 'ID_' + str(track_output[5]) statistic_dic[names[c]] += 1 label = (f'{track_id}') if hide_labels else (f'{track_id} {names[c]}') annotator.box_label(xyxy, label, color=colors(c, True)) if self.rate_check: time.sleep(1/self.rate) #保存检测结果图像或视频,并通过信号发送处理后的图像和统计数据 im0 = annotator.result() self.send_img.emit(im0) self.send_raw.emit(im0s if isinstance(im0s, np.ndarray) else im0s[0]) self.send_statistic.emit(statistic_dic) if self.save_fold: os.makedirs(self.save_fold, exist_ok=True) if self.vid_cap is None: save_path = os.path.join(self.save_fold, time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime()) + '.jpg') cv2.imwrite(save_path, im0) else: if count == 1: ori_fps = int(self.vid_cap.get(cv2.CAP_PROP_FPS)) if ori_fps == 0: ori_fps = 25 # width = int(self.vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) # height = int(self.vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) width, height = im0.shape[1], im0.shape[0] save_path = os.path.join(self.save_fold, time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime()) + '.mp4') self.out = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), ori_fps, (width, height)) self.out.write(im0) if percent == self.percent_length: print(count) self.send_percent.emit(0) self.send_msg.emit('结束') if hasattr(self, 'out'): self.out.release() break except Exception as e: self.send_msg.emit('%s' % e) class MainWindow(QMainWindow, Ui_mainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.m_flag = False # style 1: window can be stretched # self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint) # style 2: window can not be stretched self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint | Qt.WindowSystemMenuHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint) # self.setWindowOpacity(0.85) # Transparency of window self.minButton.clicked.connect(self.showMinimized) self.maxButton.clicked.connect(self.max_or_restore) # show Maximized window self.maxButton.animateClick(10) self.closeButton.clicked.connect(self.close) self.qtimer = QTimer(self) self.qtimer.setSingleShot(True) self.qtimer.timeout.connect(lambda: self.statistic_label.clear()) # search models automatically self.comboBox.clear() self.pt_list = os.listdir('./pt') self.pt_list = [file for file in self.pt_list if file.endswith('.pt')] self.pt_list.sort(key=lambda x: os.path.getsize('./pt/'+x)) self.comboBox.clear() self.comboBox.addItems(self.pt_list) self.qtimer_search = QTimer(self) self.qtimer_search.timeout.connect(lambda: self.search_pt()) self.qtimer_search.start(2000) # yolov5 thread self.det_thread = DetThread() self.model_type = self.comboBox.currentText() self.det_thread.weights = "./pt/%s" % self.model_type self.det_thread.source = '0' self.det_thread.percent_length = self.progressBar.maximum() self.det_thread.send_raw.connect(lambda x: self.show_image(x, self.raw_video)) self.det_thread.send_img.connect(lambda x: self.show_image(x, self.out_video)) self.det_thread.send_statistic.connect(self.show_statistic) self.det_thread.send_msg.connect(lambda x: self.show_msg(x)) self.det_thread.send_percent.connect(lambda x: self.progressBar.setValue(x)) self.det_thread.send_fps.connect(lambda x: self.fps_label.setText(x)) self.fileButton.clicked.connect(self.open_file) self.cameraButton.clicked.connect(self.chose_cam) #self.rtspButton.clicked.connect(self.chose_rtsp) self.runButton.clicked.connect(self.run_or_continue) self.stopButton.clicked.connect(self.stop) self.comboBox.currentTextChanged.connect(self.change_model) self.confSpinBox.valueChanged.connect(lambda x: self.change_val(x, 'confSpinBox')) self.confSlider.valueChanged.connect(lambda x: self.change_val(x, 'confSlider')) self.iouSpinBox.valueChanged.connect(lambda x: self.change_val(x, 'iouSpinBox')) self.iouSlider.valueChanged.connect(lambda x: self.change_val(x, 'iouSlider')) self.rateSpinBox.valueChanged.connect(lambda x: self.change_val(x, 'rateSpinBox')) self.rateSlider.valueChanged.connect(lambda x: self.change_val(x, 'rateSlider')) self.checkBox.clicked.connect(self.checkrate) self.saveCheckBox.clicked.connect(self.is_save) self.load_setting() def search_pt(self): pt_list = os.listdir('./pt') pt_list = [file for file in pt_list if file.endswith('.pt')] pt_list.sort(key=lambda x: os.path.getsize('./pt/' + x)) if pt_list != self.pt_list: self.pt_list = pt_list self.comboBox.clear() self.comboBox.addItems(self.pt_list) def is_save(self): if self.saveCheckBox.isChecked(): self.det_thread.save_fold = './result' else: self.det_thread.save_fold = None def checkrate(self): if self.checkBox.isChecked(): self.det_thread.rate_check = True else: self.det_thread.rate_check = False def chose_cam(self): try: self.stop() MessageBox( self.closeButton, title='提示', text='加载摄像头', time=2000, auto=True).exec_() # get the number of local cameras _, cams = Camera().get_cam_num() popMenu = QMenu() popMenu.setFixedWidth(self.cameraButton.width()) popMenu.setStyleSheet(''' QMenu { font-size: 16px; font-family: "Microsoft YaHei UI"; font-weight: light; color:white; padding-left: 5px; padding-right: 5px; padding-top: 4px; padding-bottom: 4px; border-style: solid; border-width: 0px; border-color: rgba(255, 255, 255, 255); border-radius: 3px; background-color: rgba(200, 200, 200,50);} ''') for cam in cams: exec("action_%s = QAction('%s')" % (cam, cam)) exec("popMenu.addAction(action_%s)" % cam) x = self.groupBox_5.mapToGlobal(self.cameraButton.pos()).x() y = self.groupBox_5.mapToGlobal(self.cameraButton.pos()).y() y = y + self.cameraButton.frameGeometry().height() pos = QPoint(x, y) action = popMenu.exec_(pos) if action: self.det_thread.source = action.text() self.statistic_msg('加载视频:{}'.format(action.text())) except Exception as e: self.statistic_msg('%s' % e) def load_setting(self): config_file = 'config/setting.json' if not os.path.exists(config_file): iou = 0.26 conf = 0.33 rate = 10 check = 0 savecheck = 0 new_config = {"iou": iou, "conf": conf, "rate": rate, "check": check, "savecheck": savecheck } new_json = json.dumps(new_config, ensure_ascii=False, indent=2) with open(config_file, 'w', encoding='utf-8') as f: f.write(new_json) else: config = json.load(open(config_file, 'r', encoding='utf-8')) if len(config) != 5: iou = 0.26 conf = 0.33 rate = 10 check = 0 savecheck = 0 else: iou = config['iou'] conf = config['conf'] rate = config['rate'] check = config['check'] savecheck = config['savecheck'] self.confSpinBox.setValue(conf) self.iouSpinBox.setValue(iou) self.rateSpinBox.setValue(rate) self.checkBox.setCheckState(check) self.det_thread.rate_check = check self.saveCheckBox.setCheckState(savecheck) self.is_save() def change_val(self, x, flag): if flag == 'confSpinBox': self.confSlider.setValue(int(x*100)) elif flag == 'confSlider': self.confSpinBox.setValue(x/100) self.det_thread.conf_thres = x/100 elif flag == 'iouSpinBox': self.iouSlider.setValue(int(x*100)) elif flag == 'iouSlider': self.iouSpinBox.setValue(x/100) self.det_thread.iou_thres = x/100 elif flag == 'rateSpinBox': self.rateSlider.setValue(x) elif flag == 'rateSlider': self.rateSpinBox.setValue(x) self.det_thread.rate = x * 10 else: pass def statistic_msg(self, msg): self.statistic_label.setText(msg) # self.qtimer.start(3000) def show_msg(self, msg): self.runButton.setChecked(Qt.Unchecked) self.statistic_msg(msg) if msg == "Finished": self.saveCheckBox.setEnabled(True) def change_model(self, x): self.model_type = self.comboBox.currentText() self.det_thread.weights = "./pt/%s" % self.model_type self.statistic_msg('Change model to %s' % x) def open_file(self): config_file = 'config/fold.json' # config = json.load(open(config_file, 'r', encoding='utf-8')) config = json.load(open(config_file, 'r', encoding='utf-8')) open_fold = config['open_fold'] if not os.path.exists(open_fold): open_fold = os.getcwd() name, _ = QFileDialog.getOpenFileName(self, 'Video/image', open_fold, "Pic File(*.mp4 *.mkv *.avi *.flv " "*.jpg *.png)") if name: self.det_thread.source = name self.statistic_msg('Loaded file:{}'.format(os.path.basename(name))) config['open_fold'] = os.path.dirname(name) config_json = json.dumps(config, ensure_ascii=False, indent=2) with open(config_file, 'w', encoding='utf-8') as f: f.write(config_json) self.stop() def max_or_restore(self): if self.maxButton.isChecked(): self.showMaximized() else: self.showNormal() def run_or_continue(self): self.det_thread.jump_out = False if self.runButton.isChecked(): self.saveCheckBox.setEnabled(False) self.det_thread.is_continue = True if not self.det_thread.isRunning(): self.det_thread.start() source = os.path.basename(self.det_thread.source) source = 'camera' if source.isnumeric() else source self.statistic_msg('正在检测 >> 模型:{},文件:{}'. format(os.path.basename(self.det_thread.weights), source)) else: self.det_thread.is_continue = False self.statistic_msg('暂停') def stop(self): self.det_thread.jump_out = True self.saveCheckBox.setEnabled(True) def mousePressEvent(self, event): self.m_Position = event.pos() if event.button() == Qt.LeftButton: if 0 < self.m_Position.x() < self.groupBox.pos().x() + self.groupBox.width() and \ 0 < self.m_Position.y() < self.groupBox.pos().y() + self.groupBox.height(): self.m_flag = True def mouseMoveEvent(self, QMouseEvent): if Qt.LeftButton and self.m_flag: self.move(QMouseEvent.globalPos() - self.m_Position) def mouseReleaseEvent(self, QMouseEvent): self.m_flag = False @staticmethod def show_image(img_src, label): try: ih, iw, _ = img_src.shape w = label.geometry().width() h = label.geometry().height() # keep original aspect ratio if iw/w > ih/h: scal = w / iw nw = w nh = int(scal * ih) img_src_ = cv2.resize(img_src, (nw, nh)) else: scal = h / ih nw = int(scal * iw) nh = h img_src_ = cv2.resize(img_src, (nw, nh)) frame = cv2.cvtColor(img_src_, cv2.COLOR_BGR2RGB) img = QImage(frame.data, frame.shape[1], frame.shape[0], frame.shape[2] * frame.shape[1], QImage.Format_RGB888) label.setPixmap(QPixmap.fromImage(img)) except Exception as e: print(repr(e)) def show_statistic(self, statistic_dic): try: self.resultWidget.clear() statistic_dic = sorted(statistic_dic.items(), key=lambda x: x[1], reverse=True) statistic_dic = [i for i in statistic_dic if i[1] > 0] results = [' '+str(i[0]) + ':' + str(i[1]) for i in statistic_dic] self.resultWidget.addItems(results) except Exception as e: print(repr(e)) def closeEvent(self, event): self.det_thread.jump_out = True config_file = 'config/setting.json' config = dict() config['iou'] = self.confSpinBox.value() config['conf'] = self.iouSpinBox.value() config['rate'] = self.rateSpinBox.value() config['check'] = self.checkBox.checkState() config['savecheck'] = self.saveCheckBox.checkState() config_json = json.dumps(config, ensure_ascii=False, indent=2) with open(config_file, 'w', encoding='utf-8') as f: f.write(config_json) MessageBox( self.closeButton, title='提示', text='正在关闭程序', time=2000, auto=True).exec_() sys.exit(0) if __name__ == "__main__": app = QApplication(sys.argv) myWin = MainWindow() myWin.show() # myWin.showMaximized() sys.exit(app.exec_())
05-30
To convert a DOCX file to an HTML file using docx4j, you can follow these steps: 1. Add the docx4j dependency to your project. You can do this by including the following Maven dependency in your project's pom.xml file: ```xml <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j</artifactId> <version>8.2.10</version> </dependency> ``` 2. Load the DOCX file using docx4j. Here's an example: ```java import org.docx4j.Docx4J; import org.docx4j.convert.out.HTMLSettings; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; public class DocxToHtmlConverter { public static void main(String[] args) throws Exception { // Load the DOCX file WordprocessingMLPackage wordMLPackage = Docx4J.load(new File("input.docx")); // Setup HTML conversion options HTMLSettings htmlSettings = Docx4J.createHTMLSettings(); // Convert the DOCX to HTML String htmlOutput = Docx4J.toHTML(htmlSettings, wordMLPackage.getMainDocumentPart()); // Save the HTML output to a file FileUtils.writeStringToFile(new File("output.html"), htmlOutput, "UTF-8"); } } ``` Make sure to replace "input.docx" with the path to your actual input DOCX file and "output.html" with the desired output HTML file path. 3. Run the code, and it will generate the HTML output file. Note that docx4j may not support all features of complex DOCX files, so the resulting HTML might not be an exact representation of the original document. You may need to adjust the generated HTML or use additional libraries to achieve the desired output.
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值