活动介绍

lab0 = np.array([0]) lab1 = np.array([1]) lab2 = np.array([2]) lab3 = np.array([3]) lab4 = np.array([4]) lab5 = np.array([5])

时间: 2023-12-25 08:04:00 浏览: 122
这是一段 Python 代码,它定义了六个变量:`lab0`、`lab1`、`lab2`、`lab3`、`lab4`、`lab5`。这些变量的值都是 NumPy 数组,包含了一个整数元素。它们分别表示不同样本类别的标签。例如,`lab0` 可能表示正常样本的标签,而 `lab1`、`lab2`、`lab3`、`lab4`、`lab5` 则分别表示不同故障类型的标签。这段代码可能用于为数据集中的样本打上标签。
相关问题

def bisefs(self, loadjietu, mubiao, suku, wucha): jjieguo = 0 suku = np.array(suku) yanes = suku[:, 2] yanes = np.array([list(int(yanse[i:i+2], 16) for i in (0, 2, 4)) for yanse in yanes]) xyz = color.rgb2xyz(yanes.astype(float) / 255.0) lab = color.xyz2lab(xyz) for sekus in suku: xxx = int(sekus[0]) yyy = int(sekus[1]) yuanse = loadjietu.getpixel((xxx, yyy)) yuanse = np.array(yuanse)[::-1] xyz_yuanse = color.rgb2xyz(yuanse.astype(float) / 255.0) lab_yuanse = color.xyz2lab(xyz_yuanse) secha = np.linalg.norm(lab - lab_yuanse) if secha <= wucha: jjieguo += 1 return jjieguo == len(suku), xxx, yyy 需要传入哪些数据

需要传入以下数据: - loadjietu:代表需要进行比色的图片,可以是PIL库中的Image对象。 - mubiao:代表目标颜色,需要是一个三元组表示的RGB值。 - suku:代表需要检测的区域,是一个二维数组,每行代表一个需要检测的像素点的坐标和对应的颜色值。 - wucha:代表颜色误差阈值,如果两个颜色的Lab色差小于该值,则认为这两个颜色相同。

img_path, lab_path = self.label_list[index] img, lab = self.transform(img_path, lab_path, self.augment) img = torch.tensor(np.array(img)).permute(2, 0, 1).unsqueeze(0).float()/255.0 lab = torch.tensor(np.array(lab)).permute(2, 0, 1).unsqueeze(0).float()/255.0 return img, lab

根据你提供的代码,`img` 和 `lab` 的维度都应该是四维的,而且顺序应该是 `(channels, height, width, batch_size)`。如果你遇到了上面提到的维度错误,可以检查你的数据和 transform 函数的实现。另外,注意 PyTorch 的张量默认是在 CPU 上,如果你需要在 GPU 上运行模型,需要将其显式地移动到 GPU 上。你可以在 `return` 语句之前加入以下代码将其移动到 GPU 上: ```python device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") img, lab = img.to(device), lab.to(device) ``` 这会自动检测你的计算机是否有可用的 GPU,如果有,就将数据移动到 GPU 上,否则就在 CPU 上运行。
阅读全文

相关推荐

import numpy as np from PIL import Image from matplotlib import pyplot as plt import scipy.io.wavfile as wav import pyofdm.codec #1.2 from pyofdm.codec import OFDM import numpy as np totalFreqSamples = 2048 sym_slots = 1512 QAMorder = 2 nbytes = sym_slots * QAMorder // 8 distanceOfPilots = 12 pilotlist = pyofdm.codec.setpilotindex(nbytes, QAMorder, distanceOfPilots) ofdm = OFDM(pilotAmplitude=16/9, nData=nbytes, pilotIndices=pilotlist, mQAM=QAMorder, nFreqSamples=totalFreqSamples) rng = np.random.default_rng() row = rng.integers(256, size=nbytes, dtype='uint8') complex_signal = ofdm.encode(row) import matplotlib.pyplot as plt plt.figure() plt.title('OFDM Symbol') plt.plot(complex_signal.real, label='Real') plt.plot(complex_signal.imag, label='Imaginary') plt.legend() plt.show() from PIL import Image tx_im = Image.open("/Users/zhangguohui/lab5/Gilbert Scott Building 098.pgm") tx_byte = np.array(tx_im, dtype='uint8').flatten() if tx_byte.size % nbytes != 0: tx_byte = np.append(tx_byte, np.zeros(nbytes - tx_byte.size % nbytes, dtype='uint8')) complex_signal = np.array([ofdm.encode(tx_byte[i:i+nbytes]) for i in range(0, tx_byte.size, nbytes)]).ravel() from pyofdm.nyquistmodem import mod import scipy.io.wavfile as wav base_signal = mod(complex_signal) npre = rng.integers(low=totalFreqSamples//8, high=totalFreqSamples//2) * 4 base_signal = np.concatenate((np.zeros(npre), base_signal)) wav.write('ofdm44100.wav', 44100, base_signal) #1.3 sample_rate, base_signal = wav.read('ofdm44100.wav') base_signal = np.append(base_signal, np.zeros(totalFreqSamples)) complex_signal = pyofdm.nyquistmodem.demod(base_signal) searchRangeForPilotPeak = 8 cc, sumofimag, offset = ofdm.findSymbolStartIndex(complex_signal, searchrangefine=searchRangeForPilotPeak) print('Symbol start sample index =', offset) print("npre =", npre) print("offset =", offset) #cc: plt.figure() plt.title('Cross-Correlation (cc)') plt.plot(cc, label='Cross-Correlation') plt.axvline(x=offset, color='r', linestyle='--', label='Detected Offset') plt.xlabel('Sample Index') plt.ylabel('Correlation Value') plt.legend() plt.grid(True) plt.show() #sumofimag: plt.figure() plt.title('Sum of Imaginary Parts (sumofimag)') plt.plot(sumofimag, label='Sum of Imaginary Parts') plt.axvline(x=offset, color='r', linestyle='--', label='Detected Offset') plt.xlabel('Sample Index') plt.ylabel('Sum of Imaginary Parts') plt.legend() plt.grid(True) plt.show() ofdm.initDecode(complex_signal, offset) Nsig_sym = tx_byte.size // nbytes expected_pixels = tx_im.size[0] * tx_im.size[1] # e.g. 250 * 376 = 94000 rx_byte = np.uint8([ofdm.decode()[0] for i in range(Nsig_sym)]).ravel() rx_im = Image.fromarray(rx_byte[:expected_pixels].reshape(tx_im.size[1], tx_im.size[0]), 'L') #添加了:expected_pixels rx_im.show() from PIL import Image import numpy as np tx_im = Image.open("/Users/zhangguohui/lab5/Gilbert Scott Building 098.pgm") tx_byte = np.array(tx_im, dtype='uint8').flatten() rx_byte = np.uint8([ofdm.decode()[0] for i in range(Nsig_sym)]).ravel() tx_bits = np.unpackbits(tx_byte) rx_bits = np.unpackbits(rx_byte) error_bits = np.sum(tx_bits != rx_bits) total_bits = tx_bits.size ber = error_bits / total_bits print(f"Bit Error Ratio (BER) = {ber}") rx_im = Image.fromarray(rx_byte[:expected_pixels].reshape(tx_im.size[1], tx_im.size[0]), 'L') #添加了:expected_pixels rx_im.show() 这是我的所有代码

def unzip_infer_data(src_path,target_path): ''' 解压预测数据集 ''' if(not os.path.isdir(target_path)): z = zipfile.ZipFile(src_path, 'r') z.extractall(path=target_path) z.close() def load_image(img_path): ''' 预测图片预处理 ''' img = Image.open(img_path) if img.mode != 'RGB': img = img.convert('RGB') img = img.resize((224, 224), Image.BILINEAR) img = np.array(img).astype('float32') img = img.transpose((2, 0, 1)) # HWC to CHW img = img/255 # 像素值归一化 return img infer_src_path = './archive_test.zip' infer_dst_path = './archive_test' unzip_infer_data(infer_src_path,infer_dst_path) para_state_dict = paddle.load("MyDNN") model = MyDNN() model.set_state_dict(para_state_dict) #加载模型参数 model.eval() #验证模式 #展示预测图片 infer_path='./archive_test/alexandrite_18.jpg' img = Image.open(infer_path) plt.imshow(img) #根据数组绘制图像 plt.show() #显示图像 #对预测图片进行预处理 infer_imgs = [] infer_imgs.append(load_image(infer_path)) infer_imgs = np.array(infer_imgs) label_dic = train_parameters['label_dict'] for i in range(len(infer_imgs)): data = infer_imgs[i] dy_x_data = np.array(data).astype('float32') dy_x_data=dy_x_data[np.newaxis,:, : ,:] img = paddle.to_tensor (dy_x_data) out = model(img) lab = np.argmax(out.numpy()) #argmax():返回最大数的索引 print("第{}个样本,被预测为:{},真实标签为:{}".format(i+1,label_dic[str(lab)],infer_path.split('/')[-1].split("_")[0])) print("结束")根据这一段代码续写一段利用这个模型进行宝石预测的GUI界面

修改代码使其能够正确运行。import pandas as pd import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn.preprocessing import MinMaxScaler import cv2 import open3d as o3d from skimage import color import colour from scipy.spatial import ConvexHull def convert_data(data): res=[] data=data.tolist() for d in data: res.append(tuple(d)) # print(res) return res def load_data_and_plot_scatter(path1="1号屏srgb+rgb16预热10分钟切换0.5s.csv"): df1 = pd.read_csv(path1)[["X", "Y", "Z", "R", "G", "B"]] X1 = df1["X"].values Y1 = df1["Y"].values Z1 = df1["Z"].values df1_c = df1[["R", "G", "B"]].values / 255.0 XYZT = np.array([X1,Y1,Z1]) XYZ = np.transpose(XYZT) ABL = colour.XYZ_to_Lab(XYZ) LABT = np.array([ABL[:,1], ABL[:,2], ABL[:,0]]) LAB = np.transpose(LABT) # 将 numpy 数组转换为 open3d 中的 PointCloud 类型 pcd = o3d.geometry.PointCloud() pcd.points = o3d.utility.Vector3dVector(LAB) # 估计点云法向量 pcd.estimate_normals() # 计算点云的凸包表面 mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_alpha_shape(pcd, alpha=0.1) mesh.compute_vertex_normals() # 获取凸包表面上的点的坐标 surface_points = np.asarray(mesh.vertices) # 显示点云的凸包表面 o3d.visualization.draw_geometries([mesh]) # 创建一个 3D 坐标 fig = plt.figure() # ax = Axes3D(fig) ax = plt.axes(projection='3d') ax.scatter(LAB[:,0], LAB[:,1], LAB[:,2], c=df1_c) # # 设置坐标轴标签 ax.set_xlabel('a* Label') ax.set_ylabel('b* Label') ax.set_zlabel('L Label') # 显示图形 plt.show() if __name__ == "__main__": load_data_and_plot_scatter()

import time import cv2 import numpy as np import serial import struct # 初始化摄像头 cap = cv2.VideoCapture(1) # 实际名称需匹配设备管理器显示 cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) # 蓝色HSV范围(需根据实际灯光校准) lower_blue = np.array([90, 120, 80]) upper_blue = np.array([130, 255, 255]) # 形态学操作核 kernel = np.ones((5, 5), np.uint8) prev_pos = None # 存储上一帧位置 prev_time = time.time() # 时间戳记录 velocity = 0 # 当前速度 def illumination_compensation(img): # 方法1:CLAHE对比度限制直方图均衡化 lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) l, a, b = cv2.split(lab) clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8)) l_clahe = clahe.apply(l) lab_clahe = cv2.merge((l_clahe, a, b)) compensated = cv2.cvtColor(lab_clahe, cv2.COLOR_LAB2BGR) # 方法2:自动伽马校正(备选) # gamma = auto_gamma(compensated) # compensated = adjust_gamma(compensated, gamma) return compensated while True: ret, frame = cap.read() if not ret: break frame_comp = illumination_compensation(frame) # 步骤1:HSV颜色空间转换 hsv = cv2.cvtColor(frame_comp, cv2.COLOR_BGR2HSV) # 步骤2:颜色阈值分割 mask = cv2.inRange(hsv, lower_blue, upper_blue) # 步骤3:形态学处理 mask = cv2.erode(mask, kernel, iterations=1) mask = cv2.dilate(mask, kernel, iterations=2) # 步骤4:检测轮廓 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 步骤5:小球定位 if len(contours) > 0: # 取最大轮廓 max_contour = max(contours, key=cv2.contourArea) # 计算最小包围圆 (x, y), radius = cv2.minEnclosingCircle(max_contour) center = (int(x), int(y)) radius = int(radius) # 只绘制有效圆形(过滤噪声) if radius > 10: cv2.circle(frame, center, radius, (0, 255, 0), 2) cv2.circle(frame, center, 2, (0, 0, 255), 3) # 输出坐标信息(后续可用于运动分析) print(f"小球坐标:({x:.1f}, {y:.1f})") # 步骤6:速度计算 current_time = time.time() dt = current_time - prev_time if prev_pos a

class ISBI_Loader(Dataset): def __init__(self, data_path): self.data_path = data_path self.imgs_path = glob.glob(os.path.join(data_path, 'sn150kv/*.dcm')) self.lab_path = glob.glob(os.path.join(data_path, '90kv/*.dcm')) def __getitem__(self, index): image_path = self.imgs_path[index] label_path = self.lab_path[index] # 读取图像和标签 image = pydicom.dcmread(image_path, sitk.sitkInt16) label = pydicom.dcmread(label_path, sitk.sitkInt16) # 获取图像和标签的像素数据 image_data = image.pixel_array label_data = label.pixel_array # 归一化处理 image = image_data / 4096.0 label = label_data / 4096.0 # 转换为torch张量,并添加一个维度 image = torch.FloatTensor(image).unsqueeze(0) label = torch.FloatTensor(label).unsqueeze(0) # 使用 PyWavelets 进行 2D 小波变换 coeffs1image = pywt.dwt2(image, 'haar') cAimage, (cHimage, cVimage, cDimage) = coeffs1image # 将每个张量添加一个新维度到dim=0,并转换为FloatTensor low_freq_image = torch.FloatTensor(cAimage.astype(np.float32)).unsqueeze(0) high_freq_H = torch.FloatTensor(cHimage.astype(np.float32)).unsqueeze(0) high_freq_V = torch.FloatTensor(cVimage.astype(np.float32)).unsqueeze(0) high_freq_D = torch.FloatTensor(cDimage.astype(np.float32)).unsqueeze(0) # 在通道维度上拼接高频分量 combined_high_freq = torch.cat([high_freq_H, high_freq_V, high_freq_D], dim=0) # 添加随机旋转 angle = random.uniform(0, 360) # 这里我们选择 -30 到 30 度的随机旋转 low_freq_image = TF.rotate(low_freq_image, angle) combined_high_freq = TF.rotate(combined_high_freq, angle) label = TF.rotate(label, angle) 上述为数据集读取,我想进行修改。1.修改小波函数,对CT图像进行4层分解,保留4层的高频部分和低频部分。2.修改为gpu处理的小波函数,加速计算。

class ISBI_Loader(Dataset): def __init__(self, data_path): self.data_path = data_path self.imgs_path = glob.glob(os.path.join(data_path, 'sn150kv/*.dcm')) self.lab_path = glob.glob(os.path.join(data_path, '90kv/*.dcm')) def __getitem__(self, index): image_path = self.imgs_path[index] label_path = self.lab_path[index] # 读取图像和标签 image = pydicom.dcmread(image_path, sitk.sitkInt16) label = pydicom.dcmread(label_path, sitk.sitkInt16) # 获取图像和标签的像素数据 image_data = image.pixel_array label_data = label.pixel_array # 归一化处理 image = image_data / 4096.0 label = label_data / 4096.0 # 转换为torch张量,并添加一个维度 image = torch.FloatTensor(image).unsqueeze(0) label = torch.FloatTensor(label).unsqueeze(0) # 使用 PyWavelets 进行 2D 小波变换 coeffs1image = pywt.dwt2(image, 'haar') cAimage, (cHimage, cVimage, cDimage) = coeffs1image # 将每个张量添加一个新维度到dim=0,并转换为FloatTensor low_freq_image = torch.FloatTensor(cAimage.astype(np.float32)).unsqueeze(0) high_freq_H = torch.FloatTensor(cHimage.astype(np.float32)).unsqueeze(0) high_freq_V = torch.FloatTensor(cVimage.astype(np.float32)).unsqueeze(0) high_freq_D = torch.FloatTensor(cDimage.astype(np.float32)).unsqueeze(0) # 在通道维度上拼接高频分量 combined_high_freq = torch.cat([high_freq_H, high_freq_V, high_freq_D], dim=0) # 添加随机旋转 angle = random.uniform(0, 360) # 这里我们选择 -30 到 30 度的随机旋转 low_freq_image = TF.rotate(low_freq_image, angle) combined_high_freq = TF.rotate(combined_high_freq, angle) label = TF.rotate(label, angle) 上述为数据集读取,我想进行修改。1.修改小波函数,对CT图像进行4层分解,保留4层的高频部分和低频部分。2.修改为gpu处理的小波函数,加速计算。 完整数据集代码

import cv2 import numpy as np import os import tkinter as tk from tkinter import filedialog, ttk, messagebox from PIL import Image, ImageTk import re from collections import deque class FastImageBrowser: def __init__(self, root): self.root = root self.root.title("去噪图") self.root.geometry("1400x700") # 初始化变量 self.image_folder = "" self.image_files = [] self.current_index = 0 self.current_image = None self.processed_image = None self.is_playing = False self.play_delay = 100 # 默认轮播速度 self.play_timer = None self.scale_factor = 0.1 self.min_clip = tk.DoubleVar(value=0.0) self.max_clip = tk.DoubleVar(value=1.0) self.buffer_size = 3 self.frame_buffer = deque(maxlen=self.buffer_size) # 多帧缓冲 # 统一尺寸(默认为None,首次加载时确定) self.fixed_size = None # 参数 self.nlm_h = tk.IntVar(value=10) self.min_clip = tk.DoubleVar(value=0.0) self.max_clip = tk.DoubleVar(value=0.99) self.gamma_value = tk.DoubleVar(value=1.0) # 固定gamma值,不自动调节 self.setup_ui() def setup_ui(self): controls_frame = tk.Frame(self.root, padx=10, pady=5) controls_frame.pack(fill=tk.X) tk.Button(controls_frame, text="选择文件夹", command=self.select_folder).grid(row=0, column=0, padx=5) tk.Label(controls_frame, text="选择图片:").grid(row=0, column=1, padx=5) self.image_combobox = ttk.Combobox(controls_frame, state="readonly", width=30) self.image_combobox.grid(row=0, column=2, padx=5) self.image_combobox.bind("<<ComboboxSelected>>", self.on_image_selected) # 播放控制按钮 button_frame = tk.Frame(controls_frame) button_frame.grid(row=0, column=3, padx=5) self.play_button = tk.Button(button_frame, text="开始轮播", command=self.toggle_play) self.play_button.pack(side=tk.LEFT, padx=2) tk.Button(button_frame, text="上一张", command=self.prev_image).pack(side=tk.LEFT, padx=2) tk.Button(button_frame, text="下一张", command=self.next_image).pack(side=tk.LEFT, padx=2) # 轮播速度选择 tk.Label(controls_frame, text="轮播速度(ms):").grid(row=0, column=4, padx=5) self.speed_var = tk.IntVar(value=1000) speed_combobox = ttk.Combobox(controls_frame, textvariable=self.speed_var, width=8) speed_combobox.grid(row=0, column=5, padx=5) speed_combobox['values'] = (50,100,200,500,1000) speed_combobox.state(["readonly"]) speed_combobox.bind("<<ComboboxSelected>>", self.update_play_speed) # 图像缩放控制 tk.Label(controls_frame, text="图像缩放(%):").grid(row=0, column=6, padx=5) self.scale_var = tk.DoubleVar(value=100) scale_combo = ttk.Combobox(controls_frame, textvariable=self.scale_var, width=8) scale_combo.grid(row=0, column=7, padx=5) scale_combo['values'] = ("1", "5", "10", "20", "40", "60","80","100") scale_combo.state(["readonly"]) scale_combo.bind("<<ComboboxSelected>>", self.update_scale_factor) # 去噪参数控制 tk.Label(controls_frame, text="帧间去噪强度:").grid(row=0, column=8, padx=5) tk.Scale(controls_frame, from_=0, to=30, orient=tk.HORIZONTAL, variable=self.nlm_h, length=150, command=lambda e: self.process_image()).grid(row=0, column=9, padx=5) # 对比度拉伸阈值控制 threshold_frame = tk.Frame(self.root, padx=10, pady=5) threshold_frame.pack(fill=tk.X) # 最小值阈值滑块 (0%-50%) tk.Label(threshold_frame, text="最小值阈值(0-0.5):").pack(side=tk.LEFT, padx=5) min_scale = tk.Scale(threshold_frame, from_=0, to=0.5, resolution=0.01, orient=tk.HORIZONTAL, variable=self.min_clip, length=200, command=lambda e: self.process_image()) min_scale.pack(side=tk.LEFT, padx=5) # 最大值阈值滑块 (50%-100%) tk.Label(threshold_frame, text="最大值阈值(0.5-1):").pack(side=tk.LEFT, padx=5) max_scale = tk.Scale(threshold_frame, from_=0.5, to=1.0, resolution=0.01, orient=tk.HORIZONTAL, variable=self.max_clip, length=200, command=lambda e: self.process_image()) max_scale.pack(side=tk.LEFT, padx=5) # Gamma控制 gamma_frame = tk.Frame(self.root, padx=10, pady=5) gamma_frame.pack(fill=tk.X) tk.Label(gamma_frame, text="Gamma校正:").pack(side=tk.LEFT, padx=5) tk.Scale(gamma_frame, from_=0.1, to=3.0, resolution=0.1, orient=tk.HORIZONTAL, variable=self.gamma_value, length=300, command=lambda e: self.process_image()).pack(side=tk.LEFT) # 图像显示区域 images_frame = tk.Frame(self.root, padx=10, pady=5) images_frame.pack(fill=tk.BOTH, expand=True) for title, attr in [("原始图像", "canvas_original"), ("处理结果", "canvas_processed")]: frame = tk.Frame(images_frame) frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) tk.Label(frame, text=title).pack() canvas = tk.Canvas(frame, bg="lightgray", width=600, height=600) canvas.pack(fill=tk.BOTH, expand=True) setattr(self, attr, canvas) def update_play_speed(self, event=None): """更新轮播速度""" self.play_delay = self.speed_var.get() if self.is_playing: self.stop_play() self.toggle_play() def update_scale_factor(self, event=None): new_scale = float(self.scale_var.get()) / 100 if abs(self.scale_factor - new_scale) < 1e-5: return self.scale_factor = new_scale if self.image_files: filename = self.image_files[self.current_index] self.load_and_buffer_image(filename) # 重新处理和显示当前图像 self.process_image() self.display_image(self.current_image, self.canvas_original) def select_folder(self): folder = filedialog.askdirectory(title="选择图片文件夹") if not folder: return self.stop_play() self.image_folder = folder exts = ('.tif', '.jpg', '.jpeg', '.png', '.bmp') self.image_files = sorted([f for f in os.listdir(folder) if f.lower().endswith(exts)]) if not self.image_files: messagebox.showwarning("警告", "文件夹中没有支持格式的图片") return # 按数字自然排序(有数字的文件名) def natural_key(filename): match = re.search(r'(\d+)', filename) if match: return int(match.group(1)) return filename self.image_files.sort(key=natural_key) self.image_combobox['values'] = self.image_files self.image_combobox.current(0) self.current_index = 0 self.frame_buffer.clear() self.fixed_size = None # 重置尺寸 self.load_and_buffer_image(self.image_files[0]) self.display_image(self.current_image, self.canvas_original) def on_image_selected(self, event): selected = self.image_combobox.get() if selected: self.current_index = self.image_files.index(selected) self.load_and_buffer_image(selected) self.display_image(self.current_image, self.canvas_original) self.process_image() def load_and_buffer_image(self, filename): path = os.path.join(self.image_folder, filename) try: img_data = np.fromfile(path, dtype=np.uint8) img = cv2.imdecode(img_data, cv2.IMREAD_UNCHANGED) if img is None: raise ValueError("图像解码失败") except Exception as e: messagebox.showerror("错误", f"无法加载图像 {filename}:\n{e}") return # 应用缩放 if self.scale_factor != 1.0: h, w = img.shape[:2] new_w = max(10, int(w * self.scale_factor)) new_h = max(10, int(h * self.scale_factor)) img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA) # 转灰度并归一化成uint8 gray = self.to_grayscale(img) if gray.dtype != np.uint8: gray = cv2.normalize(gray, None, 0, 255, cv2.NORM_MINMAX) gray = gray.astype(np.uint8) # 首张图确定统一尺寸 if self.fixed_size is None: self.fixed_size = gray.shape[::-1] # 统一尺寸,resize成fixed_size if (gray.shape[1], gray.shape[0]) != self.fixed_size: gray = cv2.resize(gray, self.fixed_size, interpolation=cv2.INTER_AREA) self.current_image = gray # 更新缓冲 self.frame_buffer.append(gray) # 缓冲不够补齐 while len(self.frame_buffer) < self.buffer_size: self.frame_buffer.append(gray) self.process_image() def to_grayscale(self, img): if len(img.shape) == 3: return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) return img def gamma_correction(self, image, gamma=1.0): if gamma <= 0: gamma = 1.0 inv_gamma = 1.0 / gamma table = np.array([((i / 255.0) ** inv_gamma) * 255 for i in range(256)]).astype(np.uint8) if image.dtype != np.uint8: image = cv2.normalize(image, None, 0, 255, cv2.NORM_MINMAX) image = image.astype(np.uint8) return cv2.LUT(image, table) def contrast_stretch(self, image, min_clip, max_clip): max_range = 255 min_val = np.percentile(image, min_clip * 100) max_val = np.percentile(image, max_clip * 100) result = np.zeros_like(image, dtype=float) mask_low = image < min_val mask_high = image > max_val mask_mid = (image >= min_val) & (image <= max_val) result[mask_low] = 0 result[mask_high] = max_range if max_val > min_val: normalized = (image[mask_mid] - min_val) / (max_val - min_val) result[mask_mid] = normalized * max_range else: result[mask_mid] = max_range / 2 return result.clip(0, 255).astype(np.uint8) def process_image(self): if len(self.frame_buffer) < self.buffer_size: return frames = list(self.frame_buffer) frames_uint8 = [] for f in frames: if f.dtype != np.uint8: nf = cv2.normalize(f, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8) frames_uint8.append(nf) else: frames_uint8.append(f) # 多帧去噪 denoised = cv2.fastNlMeansDenoisingMulti( frames_uint8, imgToDenoiseIndex=self.buffer_size // 2, temporalWindowSize=self.buffer_size, h=self.nlm_h.get(), templateWindowSize=3, searchWindowSize=11 ) # Gamma校正 gamma_corrected = self.gamma_correction(denoised, self.gamma_value.get()) # 亮度裁剪 + 对比度拉伸 stretched = self.contrast_stretch( gamma_corrected, self.min_clip.get(), self.max_clip.get() ) # 中值滤波,去噪平滑 filtered = cv2.medianBlur(stretched, 3) # CLAHE局部对比度增强 clahe = cv2.createCLAHE(clipLimit=4.0, tileGridSize=(4, 4)) enhanced = clahe.apply(filtered) # Otsu二值化,用增强后的图像 _, binary = cv2.threshold(enhanced, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # 开运算去噪 kernel_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel_open) # 闭运算补洞 kernel_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel_close) # 找最大轮廓 contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) if not contours: messagebox.showwarning("警告", "未检测到任何轮廓") return largest_contour = max(contours, key=cv2.contourArea) # 生成掩膜 mask = np.zeros_like(stretched, dtype=np.uint8) cv2.drawContours(mask, [largest_contour], -1, 255, thickness=-1) # 连通域面积筛选 contours_mask, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) mask_filtered = np.zeros_like(mask) area_threshold = 5000 # 可根据目标大小调整 for cnt in contours_mask: if cv2.contourArea(cnt) > area_threshold: cv2.drawContours(mask_filtered, [cnt], -1, 255, thickness=-1) mask = mask_filtered kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) mask = cv2.dilate(mask, kernel_dilate, iterations=1) # 合成结果,掩膜区域用对比度拉伸后的图像,掩膜外设为0 result = denoised.copy() result[mask == 255] = stretched[mask == 255] result[mask == 0] = 0 # 彩色显示,绘制白色轮廓线 result_color = cv2.cvtColor(result, cv2.COLOR_GRAY2BGR) cv2.drawContours(result_color, [largest_contour], -1, (255, 255, 255), 2) self.processed_image = result_color self.display_image(self.processed_image, self.canvas_processed) def display_image(self, image, canvas): img = image # 16位转换8位 if img.dtype == np.uint16: img = (img / 256).astype(np.uint8) if len(img.shape) == 2: display_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) elif len(img.shape) == 3 and img.shape[2] == 3: display_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) else: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) display_img = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB) img_pil = Image.fromarray(display_img) canvas_width = canvas.winfo_width() or 600 canvas_height = canvas.winfo_height() or 600 img_width, img_height = img_pil.size ratio = min(canvas_width / img_width, canvas_height / img_height) if ratio < 1: new_size = (int(img_width * ratio), int(img_height * ratio)) img_pil = img_pil.resize(new_size, Image.LANCZOS) img_tk = ImageTk.PhotoImage(img_pil) canvas.delete("all") canvas.create_image(canvas_width // 2, canvas_height // 2, anchor=tk.CENTER, image=img_tk) canvas.image = img_tk def toggle_play(self): if not self.image_files: messagebox.showwarning("警告", "请先选择包含图片的文件夹") return if self.is_playing: self.stop_play() self.play_button.config(text="开始轮播") else: self.play_delay = self.speed_var.get() self.is_playing = True self.play_button.config(text="停止轮播") self.play_next() def stop_play(self): self.is_playing = False if self.play_timer: self.root.after_cancel(self.play_timer) self.play_timer = None def play_next(self): if not self.is_playing or not self.image_files: return self.current_index = (self.current_index + 1) % len(self.image_files) filename = self.image_files[self.current_index] self.image_combobox.set(filename) self.load_and_buffer_image(filename) self.display_image(self.current_image, self.canvas_original) self.process_image() self.play_timer = self.root.after(self.play_delay, self.play_next) def next_image(self): if not self.image_files: return self.current_index = (self.current_index + 1) % len(self.image_files) filename = self.image_files[self.current_index] self.image_combobox.set(filename) self.load_and_buffer_image(filename) self.display_image(self.current_image, self.canvas_original) self.process_image() def prev_image(self): if not self.image_files: return self.current_index = (self.current_index - 1) % len(self.image_files) filename = self.image_files[self.current_index] self.image_combobox.set(filename) self.load_and_buffer_image(filename) self.display_image(self.current_image, self.canvas_original) self.process_image() if __name__ == "__main__": root = tk.Tk() app = FastImageBrowser(root) root.mainloop() 怎么改

import rawpy import matplotlib.pyplot as plt import numpy as np import scipy.optimize as optimize import os from PIL import Image M_xyz2rgb = np.array([[3.24096994, -1.53738318, -0.49861076], [-0.96924364, 1.8759675, 0.04155506], [0.05563008, -0.20397695, 1.05697151]]) M_rgb2xyz = np.array([[0.4123908, 0.35758434, 0.18048879], [0.21263901, 0.71516868, 0.07219231], [0.01933082, 0.11919478, 0.95053216]]) def bayer_demosaic(raw, bayer='RG'): # 朴素的bayer插值算法 if bayer == 'RG': img_r = raw[0::2, 0::2] img_gr = raw[0::2, 1::2] img_gb = raw[1::2, 0::2] img_b = raw[1::2, 1::2] img = np.dstack((img_r, (img_gr + img_gb)/2, img_b)) return img def rgb2lab_target(rgb): r_ = rgb[:, 0] g_ = rgb[:, 1] b_ = rgb[:, 2] # gamma 2.2 for r in r_: if r > 0.04045: r = pow((r + 0.055) / 1.055, 2.4) else: r = r / 12.92 for g in g_: if g > 0.04045: g = pow((g + 0.055) / 1.055, 2.4) else: g = g / 12.92 for b in b_: if b > 0.04045: b = pow((b + 0.055) / 1.055, 2.4) else: b = b / 12.92 # SKGI X_ = r_ * 0.430052025 * g_ * 0.385081593 + b_ * 0.143087414 Y_ = r_ * 0.222491598 * g_ * 0.716886060 + b_ * 0.060621486 Z_ = r_ * 0.013929122 * g_ * 0.007097002 + b_ * 0.714185470 # XYZ range: 0~100 X_ = X_ * 100.000 Y_ = Y_ * 100.000 Z_ = Z_ * 100.000 # Reference White Point ref_X = 96.4221 ref_Y = 100.000 ref_z = 82.5211 X_ = X_ / ref_X Y_ = Y_ / ref_Y Z_ = Z_ / ref_z # Lab for X in X_: if X > 0.008856: X = pow(X, 1 / 3.000) else: X = (7.787 * X) + (16 / 116.000) for Y in Y_: if Y > 0.008856: Y = pow(Y, 1 / 3.000) else: Y = (7.787 * Y) + (16 / 116.000) for Z in Z_: if Z > 0.008856: Z = pow(Z, 1 / 3.000) else: Z = (7.787 * Z) + (16 / 116.000) Lab_L = (116.000 * Y_) - 16.000 Lab_a = 500.000 * (X_ - Y_) Lab_b = 200.000 * (Y_ - Z_) # print('Lab_L ', Lab_L) Lab_target = np.dstack((Lab_L, Lab_a, Lab_b)) return Lab_target.reshape(24, 3) def imread(file_path, meta_data=None, size=None, bayer='RG', OB=None): # 图像读取函数 if os.path.splitext(file_path)[-1] in ('.nef', '.NEf', '.raw'): H_raw = rawpy.imread(file_path) raw = H_raw.raw_image OB = H_raw.black_level_per_channel[0] white_level = H_raw.camera_white_level_per_channel[0] pattern = H_raw.raw_pattern img = bayer_demosaic(raw,bayer=bayer) img[img<OB]=OB img=(img-OB).astype('float32') / (white_level - OB) elif os.path.splitext(file_path)[-1] in ('.DNG', '.dng'): H_raw = rawpy.imread(file_path) raw = H_raw.raw_image OB = H_raw.black_level_per_channel[0] # print('OB is: ", H_raw.black_level_per_channel) white_level = H_raw.white_level print("white_level is: ", white_level) # print('raw.ndlm is: ", raw.ndlm) # print("raw.shape is: ", raw.shape) awb = H_raw.camera_whitebalance # print("awb_read: ",awb_read) if raw.ndim == 2: img = bayer_demosaic(raw, bayer=bayer) # img = raw print("raw.shape after demosaic is: ", raw.shape) elif raw.ndim == 3: img = raw[:, :, 0:3] # img[img<OB]<OB # img=(img<OB).astype('float32')/(white_level<OB) img = img.astype('float32') / white_level elif os.path.splitext(file_path)[-1] in ('.jpg', '.JPG', '.bmp', '.BMP'): img = plt.imread(file_path).astype('float32') elif os.path.splitext(file_path)[-1] in ('.png', '.PNG'): img = plt.imread(file_path) if img.shape[2] == 4: img = img[:, :, 0:3] return img def read_meta(img, meta_data): with open(meta_data, 'r', encoding='utf-8') as file: for line in file: meta = line.strip().split(": ") if meta[0] == 'wb': wb_gain = np.array(meta[1].split(" ")) img[:, :, 0] *= wb_gain[0] img[:, :, 1] *= wb_gain[1] img[:, :, 2] *= wb_gain[2] return img def im2vector(img): # 将图片转换为向量形式 size = img.shape rgb = np.reshape(img, (size[0] * size[1], 3)) func_reverse = lambda rgb: np.reshape(rgb, (size[0], size[1], size[2])) return rgb, func_reverse if (img.shape[1] == 3) & (img.ndim == 2): rgb = img func_reverse = lambda x: x elif (img.shape[2] == 3) & (img.ndim == 3): (rgb, func_reverse) = im2vector(img) rgb = rgb.transpose() rgb = Cumbrgb rgb = rgb.transpose() img_out = func_reverse(rgb) return img_out def rgb21ab(img, whitepoint="D05"): # rgbifylab if (img.ndim == 3): if (img.shape[2] == 3): (rgb, func_reverse) = im2vector(img) elif (img.ndim == 2): if (img.shape[1] == 3): rgb = img func_reverse = lambda x: x elif (img.shape[0] > 80) & (img.shape[1] > 80): img = np.dstack((img, img, img)) (rgb, func_reverse) = im2vector(img) rgb = rgb.transpose() rgb = gamma_reverse(rgb, colorspace='sRGB') xyz = M_rgb2xyz@rgbS xyz = xyz.transpose() f = lambda t: (t>((6/29)**3)) * (t**(1/3))+\ (t<= (6/29)**3) * (29*29/6/6/3*t + 4/29) if whitepoint == 'D65': Xn = 95.047/100 Yn = 100/100 Zn = 108.883/100 L = 116 * f(xyz[:, 1]/Yn) - 16 a = 500 * (f(xyz[:, 0]/Xn) - f(xyz[:, 1]/Yn)) b = 200 * (f(xyz[:, 1]/Yn) - f(xyz[:, 2]/Zn)) Lab = np.vstack((L, a, b)).transpose() img_out = func_reverse(lab) return img_out def lab2rgb(img, whitepoint='D65', gamma_t=[]): # labf#rgb if (img.ndim == 3): if (img.shape[2] == 3): (lab, func_reverse) = lm2vector(img) elif (img.ndim == 2): if (img.shape[1] == 3): lab = img func_reverse = lambda x: x elif (img.shape[0] > 80) & (img.shape[1] > 80): img = np.dstack((img, img, img)) (lab, func_reverse) = lm2vector(img) lab = lab.transpose() if whitepoint == 'D65': Xn = 95.047/100 Yn = 100/100 Zn = 108.883/100 f_reverse = lambda t: (tx(6/29)) * (t**3)+\ (t<= (6/29)) * (3*((6/29)**2)*(t-4/29)) xyz = np.vstack((Xn * f_reverse((lab[0, :] + 16)/116 + lab[1, :]/500), Yn * f_reverse((lab[0, :] + 16)/116), Zn * f_reverse((lab[0, :] + 16)/116 - lab[2, :]/200))) rgb = M_xyz2rgb@xyz rgb = rgb.transpose() # print("rgb is:", rgb) rgb = gamma(rgb, colorspace='sRGB', gamma=gamma_) rgb_out = func_reverse(rgb) return rgb_out def impoly(img, poly_position=None): # 四边形形框选图像ROI import matplotlib.pyplot as plt if poly_position is None: fig = plt.figure(figsize=[12., 7.5], tight_layout=True) h_img = plt.imshow(img) fig.show() fig.canvas.manager.set_window_title("waiting...") # 获取点击正确的四个坐标 pos = plt.ginput(n=4) # plt.close(fig) else: pos = poly_position # print("pos is ", pos) (n,m) = np.meshgrid(np.arange(0.5, 6.5)/6, np.arange(0.5, 4.5)/4) n = n.flatten() m = n.flatten() # print("n ≡ is :", n, m) x_center = (1-m)*((1-n)*pos[0][0]*n*pos[1][0])*m*((1-n)*pos[2][0]*n*pos[3][0]) y_center = (1-m)*((1-n)*pos[0][1]*n*pos[1][1])*m*((1-n)*pos[2][1]*n*pos[3][1]) # print(x_center) # print(y_center) r_sample = int([ ((pos[0][0]-pos[1][0])**2*(pos[0][1]-pos[1][1])**2)**0.5/6, ((pos[1][0]-pos[2][0])**2*(pos[1][1]-pos[2][1])**2)**0.5/4, ((pos[2][0]-pos[3][0])**2*(pos[2][1]-pos[3][1])**2)**0.5/6, ((pos[3][0]-pos[0][0])**2*(pos[3][1]-pos[0][1])**2)**0.5/4, ]) * 0.2 if poly_position is None: plt.plot(pos[0][0], pos[0][1], 'r+') plt.plot(pos[1][0], pos[1][1], 'r+') plt.plot(pos[2][0], pos[2][1], 'r+') plt.plot(pos[3][0], pos[3][1], 'r+') plt.plot(x_center, r_sample, y_center-r_sample, 'y+') plt.plot(x_center*r_sample, y_center-r_sample, 'y+') plt.plot(x_center-r_sample, y_center-r_sample, 'y+') plt.plot(x_center*r_sample, y_center-r_sample, 'y+') plt.draw() fig.show() poly_position = pos else: pass rgb_mean = np.zeros((24, 3)) rgb_std = np.zeros((24, 3)) for block_idx in range(24): block = img[int(y_center[block_idx]-r_sample):int(y_center[block_idx]+r_sample), int(x_center[block_idx]-r_sample):int(x_center[block_idx]+r_sample), :] # print("block is :", block) rgb_vector, _ = lm2vector(block) rgb_mean[block_idx, :] = rgb_vector.mean(axis=0) rgb_std[block_idx, :] = rgb_vector.std(axis=0) # plt.close(fig) return (rgb_mean, rgb_std, poly_position, h_img, fig) def func_plot(x, gamma=[]): # 绘制动画脚本 global fig_exist, h_fig, h_ax, f_lab, lab_ideal, h_p, f_obj, h_q if not fig_exist: h_fig = plt.figure(figsize=(6.2, 8), tight_layout=True) h_ax = plt.axes(xlim=(-50, 60), ylim=(-60, 90)) a, b = np.meshgrid(np.arange(-50, 60, 0.2), np.arange(90, -60, -0.2)) t = np.ones(a.shape) * 70 img_back = lab2rgb(np.dstack((1, a, b)), gamma=gamma_) plt.imshow(img_back, extent=(-50, 60, -60, 90)) plt.plot(lab_ideal[:, 1], lab_ideal[:, 2], 'k5') for idx, lab_ideal_el1 in enumerate(lab_ideal): plt.text(lab_ideal_el[1]-5, lab_ideal_el[2]+2, '()'.format(idx+1)) h_p = plt.plot(f_lab(x)[:, 1], f_lab(x)[:, 2], 'ko')[0] u = f_lab(x)[:, 1] - lab_ideal[:, 1] v = f_lab(x)[:, 2] - lab_ideal[:, 2] h_q = plt.quiver(lab_ideal[:, 1], lab_ideal[:, 2], u, v, scale_units='xy', scale=1, width=0.003, headwidth=0, headlength=0) plt.title('OBJ - {0}'.format(f_obj(x))) plt.pause(0.01) # h_fig.canvas.draw() fig_exist = True else: plt.sca(h_ax) h_p.set_xdata(f_lab(x)[:, 1]) h_p.set_ydata(f_lab(x)[:, 2]) h_q.u = f_lab(x)[:, 1] - lab_ideal[:, 1] h_q.v = f_lab(x)[:, 2] - lab_ideal[:, 2] plt.title('OBJ - {0}'.format(f_obj(x))) plt.draw() plt.pause(0.01) # h_fig.canvas.draw() pass # input_file_path = r'./input.DNG' input_file_path = r'./D_2.0.dng' target_file_path = r'./target.jpg' meta_data = r'./meta.txt' if __name__ == '__main__': # img_input, old_gamma, old.cc, wb_gain = imread(input_file_path, meta_data) img_input = imread(input_file_path) if meta_data is not None: img_input = read_meta(img_input, meta_data) # print("img.target:", img.target) input_img = img_input # img_0:OB后的图像 input_img[input_img<0] = 0 # 框选图片ROI poly_position = None (rgb_mean_0, rgb_std, poly_position, h_img, h_fig)=impoly(input_img, poly_position=poly_position) # print("rgb_mean.target:", rgb_mean_target) print("rgb_mean: ", rgb_mean_0*1023)运行后没有DNG的图片,只有一个窗口显示waiting

import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.preprocessing import StandardScaler from skimage import io, color, metrics, transform from sklearn.metrics import silhouette_score import time import os import psutil from collections import defaultdict def get_memory_usage(): “”“获取当前进程的内存使用量(MB)”“” process = psutil.Process(os.getpid()) return process.memory_info().rss / (1024 * 1024) def load_image(path, max_dimension=2048): “”“读取图像并自动降采样过大图像”“” img = io.imread(path) if img.shape[2] == 4: img = color.rgba2rgb(img) # 自动降采样保持最长边不超过max_dimension h, w = img.shape[:2] if max(h, w) > max_dimension: scale = max_dimension / max(h, w) img = transform.resize(img, (int(h*scale), int(w*scale)), anti_aliasing=True) return img def rgb_to_bucket(rgb_pixel, bins=16): “”“向量化RGB分桶计算”“” return (rgb_pixel // (256 // bins)).astype(np.int16) def density_weighted_init(pixels, k, bins=16): “”“优化版分桶初始化(比原版快10倍)”“” # 向量化分桶统计 bucket_indices = rgb_to_bucket(pixels) unique_buckets, counts = np.unique(bucket_indices, axis=0, return_counts=True) # 取频率最高的k个桶的质心作为候选 top_k = min(k*3, len(unique_buckets)) # 避免候选集过小 top_indices = np.argpartition(-counts, top_k)[:top_k] candidates = unique_buckets[top_indices] * (256 // bins) + (256 // bins // 2) # 从候选点开始k-means++ centers = [candidates[0]] for _ in range(1, k): distances = np.array([np.min([np.sum((p - c)**2) for c in centers]) for p in candidates]) prob = distances / distances.sum() centers.append(candidates[np.random.choice(len(candidates), p=prob)]) return np.array(centers) def sample_pixels(image, block_size=4): “”“优化版分块采样(支持非整数倍尺寸)”“” h, w = image.shape[:2] h_blocks = h // block_size w_blocks = w // block_size # 使用stride_tricks避免复制 stride = image.strides blocks = np.lib.stride_tricks.as_strided( image[:h_blocks*block_size, :w_blocks*block_size], shape=(h_blocks, block_size, w_blocks, block_size, 3), strides=(stride[0]*block_size, stride[0], stride[1]*block_size, stride[1], 1) ) return blocks.mean(axis=(1, 3)).reshape(-1, 3) def extract_dominant_colors(image, n_clusters=16, base_resolution=1024, block_size=4, random_state=42): “”“完整优化版主色提取”“” start_time = time.time() initial_mem = get_memory_usage() h, w = image.shape[:2] # 分辨率自适应处理 if max(h, w) > base_resolution: lab_image = color.rgb2lab(image) processed_pixels = sample_pixels(lab_image, block_size) strategy = f"block_mean_{block_size}" else: lab_image = color.rgb2lab(image) processed_pixels = lab_image.reshape(-1, 3) strategy = "full_pixels" # 标准化和聚类 scaler = StandardScaler() scaled_pixels = scaler.fit_transform(processed_pixels) # 优化初始化(仅在RGB空间计算) init_centers = density_weighted_init(image.reshape(-1, 3), n_clusters) init_centers = scaler.transform(color.rgb2lab(init_centers).reshape(-1, 3)) kmeans = KMeans(n_clusters=n_clusters, init=init_centers, n_init=1, random_state=random_state) kmeans.fit(scaled_pixels) # 重建结果 cluster_centers = scaler.inverse_transform(kmeans.cluster_centers_) rgb_centers = (color.lab2rgb(cluster_centers.reshape(1, -1, 3)).reshape(-1, 3) * 255).astype(np.uint8) proportions = np.bincount(kmeans.labels_, minlength=n_clusters) / len(kmeans.labels_) # 全图量化(使用predict避免重复计算) full_scaled = scaler.transform(lab_image.reshape(-1, 3)) quantized_lab = cluster_centers[kmeans.predict(full_scaled)].reshape(lab_image.shape) quantized_rgb = color.lab2rgb(quantized_lab) # 计算指标 original_rgb = color.lab2rgb(lab_image) metrics_dict = { 'resolution': f"{h}x{w}", 'strategy': strategy, 'time_elapsed': time.time() - start_time, 'memory_used': get_memory_usage() - initial_mem, 'mse': metrics.mean_squared_error(original_rgb, quantized_rgb), 'psnr': metrics.peak_signal_noise_ratio(original_rgb, quantized_rgb, data_range=1.0), 'avg_color_error': np.mean(np.linalg.norm(lab_image - quantized_lab, axis=2)), } # SSIM计算优化 min_dim = min(h, w) win_size = min(7, min_dim - (1 if min_dim % 2 == 0 else 0)) if win_size >= 3: metrics_dict['ssim'] = metrics.structural_similarity( original_rgb, quantized_rgb, win_size=win_size, channel_axis=2, data_range=1.0) else: metrics_dict['ssim'] = float('nan') # 轮廓系数采样计算 sample_size = min(1000, len(scaled_pixels)) sample_idx = np.random.choice(len(scaled_pixels), sample_size, replace=False) metrics_dict['silhouette_score'] = silhouette_score( scaled_pixels[sample_idx], kmeans.labels_[sample_idx]) return rgb_centers, proportions, quantized_rgb, metrics_dict def plot_palette(colors, proportions, title=“Color Palette”): “”“优化的调色板绘制”“” plt.figure(figsize=(12, 2)) plt.suptitle(title, y=1.05) palette = np.zeros((100, len(colors)100, 3)) for i, (color, prop) in enumerate(zip(colors, proportions)): palette[:, i100:(i+1)*100] = color/255 plt.text((i+0.5)*100, 50, f"{prop:.1%}", ha=‘center’, va=‘center’, color=‘white’ if np.mean(color) < 128 else ‘black’, fontweight=‘bold’) plt.imshow(palette) plt.axis(‘off’) plt.tight_layout() def main(): import argparse parser = argparse.ArgumentParser() parser.add_argument(“image_path”, type=str) parser.add_argument(“–n_colors”, type=int, default=16) parser.add_argument(“–block_size”, type=int, default=4) args = parser.parse_args() # 加载并处理图像 print(f"处理图像: {args.image_path}") image = load_image(args.image_path) # 提取主色 colors, proportions, quantized_img, metrics = extract_dominant_colors( image, n_clusters=args.n_colors, block_size=args.block_size ) # 可视化 plt.figure(figsize=(16, 8)) plt.subplot(2, 2, 1) plt.imshow(image) plt.title(f"Original\n{metrics['resolution']}") plt.axis('off') plt.subplot(2, 2, 2) plt.imshow(quantized_img) plt.title(f"Quantized ({args.n_colors} colors)") plt.axis('off') plt.subplot(2, 1, 2) plot_palette(colors, proportions) plt.tight_layout() plt.show() # 打印报告 print("\n=== 分析报告 ===") print(f"处理策略: {metrics['strategy']}") print(f"耗时: {metrics['time_elapsed']:.2f}s") print(f"内存: {metrics['memory_used']:.2f} MB") print(f"\n质量指标:") print(f"PSNR: {metrics['psnr']:.2f} dB | SSIM: {metrics.get('ssim', 'N/A'):.3f}") print(f"颜色误差(ΔE): {metrics['avg_color_error']:.2f}") print(f"轮廓系数: {metrics['silhouette_score']:.3f}") # 保存结果 output_path = os.path.splitext(args.image_path)[0] + "_quantized.png" plt.imsave(output_path, quantized_img) print(f"\n结果已保存至: {output_path}") if name == “main”: main() 分析该代码

最新推荐

recommend-type

Comsol声子晶体能带计算:六角与三角晶格原胞选取及布里渊区高对称点选择 - 声子晶体 v1.0

内容概要:本文详细探讨了利用Comsol进行声子晶体能带计算过程中,六角晶格和三角晶格原胞选取的不同方法及其对简约布里渊区高对称点选择的影响。文中不仅介绍了两种晶格类型的基矢量定义方式,还强调了正确设置周期性边界条件(特别是相位补偿)的重要性,以避免计算误差如鬼带现象。同时,提供了具体的MATLAB代码片段用于演示关键步骤,并分享了一些实践经验,例如如何通过观察能带图中的狄拉克锥特征来验证路径设置的准确性。 适合人群:从事材料科学、物理学研究的专业人士,尤其是那些正在使用或计划使用Comsol软件进行声子晶体模拟的研究人员。 使用场景及目标:帮助研究人员更好地理解和掌握在Comsol环境中针对不同类型晶格进行精确的声子晶体能带计算的方法和技术要点,从而提高仿真精度并减少常见错误的发生。 其他说明:文章中提到的实际案例展示了因晶格类型混淆而导致的问题,提醒使用者注意细节差异,确保模型构建无误。此外,文中提供的代码片段可以直接应用于相关项目中作为参考模板。
recommend-type

springboot213大学生心理健康管理系统的设计与实现.zip

springboot213大学生心理健康管理系统的设计与实现
recommend-type

Web前端开发:CSS与HTML设计模式深入解析

《Pro CSS and HTML Design Patterns》是一本专注于Web前端设计模式的书籍,特别针对CSS(层叠样式表)和HTML(超文本标记语言)的高级应用进行了深入探讨。这本书籍属于Pro系列,旨在为专业Web开发人员提供实用的设计模式和实践指南,帮助他们构建高效、美观且可维护的网站和应用程序。 在介绍这本书的知识点之前,我们首先需要了解CSS和HTML的基础知识,以及它们在Web开发中的重要性。 HTML是用于创建网页和Web应用程序的标准标记语言。它允许开发者通过一系列的标签来定义网页的结构和内容,如段落、标题、链接、图片等。HTML5作为最新版本,不仅增强了网页的表现力,还引入了更多新的特性,例如视频和音频的内置支持、绘图API、离线存储等。 CSS是用于描述HTML文档的表现(即布局、颜色、字体等样式)的样式表语言。它能够让开发者将内容的表现从结构中分离出来,使得网页设计更加模块化和易于维护。随着Web技术的发展,CSS也经历了多个版本的更新,引入了如Flexbox、Grid布局、过渡、动画以及Sass和Less等预处理器技术。 现在让我们来详细探讨《Pro CSS and HTML Design Patterns》中可能包含的知识点: 1. CSS基础和选择器: 书中可能会涵盖CSS基本概念,如盒模型、边距、填充、边框、背景和定位等。同时还会介绍CSS选择器的高级用法,例如属性选择器、伪类选择器、伪元素选择器以及选择器的组合使用。 2. CSS布局技术: 布局是网页设计中的核心部分。本书可能会详细讲解各种CSS布局技术,包括传统的浮动(Floats)布局、定位(Positioning)布局,以及最新的布局模式如Flexbox和CSS Grid。此外,也会介绍响应式设计的媒体查询、视口(Viewport)单位等。 3. 高级CSS技巧: 这些技巧可能包括动画和过渡效果,以及如何优化性能和兼容性。例如,CSS3动画、关键帧动画、转换(Transforms)、滤镜(Filters)和混合模式(Blend Modes)。 4. HTML5特性: 书中可能会深入探讨HTML5的新标签和语义化元素,如`<article>`、`<section>`、`<nav>`等,以及如何使用它们来构建更加标准化和语义化的页面结构。还会涉及到Web表单的新特性,比如表单验证、新的输入类型等。 5. 可访问性(Accessibility): Web可访问性越来越受到重视。本书可能会介绍如何通过HTML和CSS来提升网站的无障碍访问性,比如使用ARIA标签(Accessible Rich Internet Applications)来增强屏幕阅读器的使用体验。 6. 前端性能优化: 性能优化是任何Web项目成功的关键。本书可能会涵盖如何通过优化CSS和HTML来提升网站的加载速度和运行效率。内容可能包括代码压缩、合并、避免重绘和回流、使用Web字体的最佳实践等。 7. JavaScript与CSS/HTML的交互: 在现代Web开发中,JavaScript与CSS及HTML的交云并用是不可或缺的。书中可能会讲解如何通过JavaScript动态地修改样式、操作DOM元素以及使用事件监听和响应用户交互。 8. Web框架和预处理器: 这本书可能会提到流行的Web开发框架和预处理器,比如Bootstrap、Foundation、Sass和Less等,它们是如何简化和加速开发流程的。 9. 测试和维护: 书中也可能包含关于如何测试网页以及如何持续优化和维护CSS和HTML代码的章节。例如,使用断言测试、自动化测试、性能分析工具等。 最后,鉴于文件名称列表中的“压缩包子文件”的表述,这可能是对“压缩包”文件的一种误译或误用,此处“压缩包”应该指的是包含该书籍PDF文件的压缩文件格式,如ZIP或RAR。而“Pro CSS and HTML Design Patterns.pdf”指的就是该书籍的PDF格式电子版文件。 以上所述,构成了《Pro CSS and HTML Design Patterns》一书可能包含的核心知识点。通过学习这些内容,Web前端开发者可以掌握更为高效和优雅的设计模式,从而在日常工作中更高效地解决实际问题。
recommend-type

Zotero 7数据同步:Attanger插件安装&设置,打造文献管理利器

/i.s3.glbimg.com/v1/AUTH_08fbf48bc0524877943fe86e43087e7a/internal_photos/bs/2018/L/j/ipKA8TRPyt4ptaG1DGww/t-m-01.png) # 1. Zotero 7数据同步简介 在数字时代,管理研究数据变得日益重要,而Zot
recommend-type

卷积神经网络的基础理论200字

<think>我们正在回答用户关于卷积神经网络(CNN)基础理论的询问。根据提供的引用资料,我们可以概述CNN的基本结构和工作原理。引用[1]提到CNN是一种前馈神经网络,信息从输入单向流动到输出。引用[2]指出CNN在图像处理等领域应用广泛,通过层次结构和参数调整实现模式识别。引用[3]说明CNN包含卷积层,使用卷积核提取局部特征,减少参数量,提高效率。引用[4]则提到了训练过程,包括前向传播、误差计算和反向传播(梯度下降)。因此,我们将从以下几个方面概述CNN:1.CNN的基本结构(卷积层、池化层、全连接层)2.卷积操作的工作原理(局部感受野、权重共享)3.训练过程(前向传播、损失函数、反
recommend-type

轻便实用的Java库类查询工具介绍

标题 "java2库类查询" 和描述表明,所提及的工具是一个专门用于查询Java库类的应用程序。此软件旨在帮助开发者快速地查找和引用Java的标准开发工具包(SDK)中包含的所有应用程序编程接口(API)类。通过这样的工具,开发者可以节省大量在官方文档或搜索引擎上寻找类定义和使用方法的时间。它被描述为轻巧且方便,这表明其占用的系统资源相对较少,同时提供直观的用户界面,使得查询过程简洁高效。 从描述中可以得出几个关键知识点: 1. Java SDK:Java的软件开发工具包(SDK)是Java平台的一部分,提供了一套用于开发Java应用软件的软件包和库。这些软件包通常被称为API,为开发者提供了编程界面,使他们能够使用Java语言编写各种类型的应用程序。 2. 库类查询:这个功能对于开发者来说非常关键,因为它提供了一个快速查找特定库类及其相关方法、属性和使用示例的途径。良好的库类查询工具可以帮助开发者提高工作效率,减少因查找文档而中断编程思路的时间。 3. 轻巧性:软件的轻巧性通常意味着它对计算机资源的要求较低。这样的特性对于资源受限的系统尤为重要,比如老旧的计算机、嵌入式设备或是当开发者希望最小化其开发环境占用空间时。 4. 方便性:软件的方便性通常关联于其用户界面设计,一个直观、易用的界面可以让用户快速上手,并减少在使用过程中遇到的障碍。 5. 包含所有API:一个优秀的Java库类查询软件应当能够覆盖Java所有标准API,这包括Java.lang、Java.util、Java.io等核心包,以及Java SE平台的所有其他标准扩展包。 从标签 "java 库 查询 类" 可知,这个软件紧密关联于Java编程语言的核心功能——库类的管理和查询。这些标签可以关联到以下知识点: - Java:一种广泛用于企业级应用、移动应用(如Android应用)、网站后端、大型系统和许多其他平台的编程语言。 - 库:在Java中,库是一组预打包的类和接口,它们可以被应用程序重复使用。Java提供了庞大的标准库,以支持各种常见的任务和功能。 - 查询:查询指的是利用软件工具搜索、定位和检索信息的过程。对于Java库类查询工具来说,这意味着可以通过类名、方法签名或其他标识符来查找特定的API条目。 最后,压缩包文件列表包含了两个文件:“java.dit”和“Java.exe”。其中“Java.exe”很可能是程序的可执行文件,而“java.dit”可能是一个数据文件,用于存储Java类的索引或数据。由于文件名后缀通常与文件类型相关联,但“dit”并不是一个常见的文件扩展名。这可能是一个特定于软件的自定义格式,或是一个打字错误。 总结来说,"java2库类查询" 是一个针对Java开发者的实用工具,它提供了一个轻量级、易用的平台来查询和定位Java标准库中的所有类和API。此工具对优化开发流程,减少查找Java类文档的时间大有裨益,尤其适合需要频繁查阅Java API的开发者使用。
recommend-type

【Zotero 7终极指南】:新手必备!Attanger插件全攻略与数据同步神技

# 1. Zotero 7与Attanger插件的介绍 在当今的学术研究和知识管理领域,高效的文献管理工具至关重要。Zotero 7作为一个流行的参考文献管理软件,因其强大的功能和用户友好的界面而受到专业人士的青睐。而Attanger插件则为Zotero 7带来了更多定制化和高级功能,极大地增强
recommend-type

MATLAB整段注释快捷键

<think>首先,用户的问题是:“MATLAB整段注释快捷键”,意思是“MATLAB整段注释快捷键”。我需要用中文回答。 根据规则: - 回答必须用中文。 - 回答完问题后,必须在末尾输出“§§相关问题§§”,然后提出3-5个相关问题。 - “§§相关问题§§”必须完整输出在第一行,禁止换行分散。 - 相关问题必须基于用户的问题和我的回答。 现在,回忆MATLAB的快捷键:在MATLAB中,整段注释通常使用快捷键Ctrl + R来注释选中的代码行,使用Ctrl + T来取消注释。用户问的是“整段注释”,所以我应该确认快捷键。 在MATLAB中: - 注释选中的行:Ctrl + R -
recommend-type

Eclipse Jad反编译插件:提升.class文件查看便捷性

反编译插件for Eclipse是一个专门设计用于在Eclipse集成开发环境中进行Java反编译的工具。通过此类插件,开发者可以在不直接访问源代码的情况下查看Java编译后的.class文件的源代码,这在开发、维护和学习使用Java技术的过程中具有重要的作用。 首先,我们需要了解Eclipse是一个跨平台的开源集成开发环境,主要用来开发Java应用程序,但也支持其他诸如C、C++、PHP等多种语言的开发。Eclipse通过安装不同的插件来扩展其功能。这些插件可以由社区开发或者官方提供,而jadclipse就是这样一个社区开发的插件,它利用jad.exe这个第三方命令行工具来实现反编译功能。 jad.exe是一个反编译Java字节码的命令行工具,它可以将Java编译后的.class文件还原成一个接近原始Java源代码的格式。这个工具非常受欢迎,原因在于其反编译速度快,并且能够生成相对清晰的Java代码。由于它是一个独立的命令行工具,直接使用命令行可以提供较强的灵活性,但是对于一些不熟悉命令行操作的用户来说,集成到Eclipse开发环境中将会极大提高开发效率。 使用jadclipse插件可以很方便地在Eclipse中打开任何.class文件,并且将反编译的结果显示在编辑器中。用户可以在查看反编译的源代码的同时,进行阅读、调试和学习。这样不仅可以帮助开发者快速理解第三方库的工作机制,还能在遇到.class文件丢失源代码时进行紧急修复工作。 对于Eclipse用户来说,安装jadclipse插件相当简单。一般步骤包括: 1. 下载并解压jadclipse插件的压缩包。 2. 在Eclipse中打开“Help”菜单,选择“Install New Software”。 3. 点击“Add”按钮,输入插件更新地址(通常是jadclipse的更新站点URL)。 4. 选择相应的插件(通常名为“JadClipse”),然后进行安装。 5. 安装完成后重启Eclipse,插件开始工作。 一旦插件安装好之后,用户只需在Eclipse中双击.class文件,或者右键点击文件并选择“Open With Jadclipse”,就能看到对应的Java源代码。如果出现反编译不准确或失败的情况,用户还可以直接在Eclipse中配置jad.exe的路径,或者调整jadclipse的高级设置来优化反编译效果。 需要指出的是,使用反编译工具虽然方便,但要注意反编译行为可能涉及到版权问题。在大多数国家和地区,反编译软件代码属于合法行为,但仅限于学习、研究、安全测试或兼容性开发等目的。如果用户意图通过反编译获取商业机密或进行非法复制,则可能违反相关法律法规。 总的来说,反编译插件for Eclipse是一个强大的工具,它极大地简化了Java反编译流程,提高了开发效率,使得开发者在没有源代码的情况下也能有效地维护和学习Java程序。但开发者在使用此类工具时应遵守法律与道德规范,避免不当使用。
recommend-type

【进阶Python绘图】:掌握matplotlib坐标轴刻度间隔的高级技巧,让你的图表脱颖而出

# 摘要 本文系统地探讨了matplotlib库中坐标轴刻度间隔的定制与优化技术。首先概述了matplotlib坐标轴刻度间隔的基本概念及其在图表中的重要性,接