def zeros(shape, name=None):

时间: 2024-05-07 10:19:07 浏览: 3
这是一个 Python 函数的定义,用于创建一个全零的数组。参数 shape 是一个元组,指定了数组的形状。参数 name 是一个可选参数,用于指定数组的名称。 下面是示例代码: ``` import numpy as np def zeros(shape, name=None): return np.zeros(shape, dtype=np.float32, name=name) ``` 这个函数使用了 NumPy 库中的 zeros 函数来创建全零数组,同时指定了数据类型为 32 位浮点数。如果指定了名称,则将其作为关键字参数传递给 zeros 函数。
相关问题

from scipy.sparse.linalg import eigsh, LinearOperator from scipy.sparse import isspmatrix, is_pydata_spmatrix class SVDRecommender: def init(self, k=50, ncv=None, tol=0, which='LM', v0=None, maxiter=None, return_singular_vectors=True, solver='arpack'): self.k = k self.ncv = ncv self.tol = tol self.which = which self.v0 = v0 self.maxiter = maxiter self.return_singular_vectors = return_singular_vectors self.solver = solver def svds(self, A): largest = self.which == 'LM' if not largest and self.which != 'SM': raise ValueError("which must be either 'LM' or 'SM'.") if not (isinstance(A, LinearOperator) or isspmatrix(A) or is_pydata_spmatrix(A)): A = np.asarray(A) n, m = A.shape if self.k <= 0 or self.k >= min(n, m): raise ValueError("k must be between 1 and min(A.shape), k=%d" % self.k) if isinstance(A, LinearOperator): if n > m: X_dot = A.matvec X_matmat = A.matmat XH_dot = A.rmatvec XH_mat = A.rmatmat else: X_dot = A.rmatvec X_matmat = A.rmatmat XH_dot = A.matvec XH_mat = A.matmat dtype = getattr(A, 'dtype', None) if dtype is None: dtype = A.dot(np.zeros([m, 1])).dtype else: if n > m: X_dot = X_matmat = A.dot XH_dot = XH_mat = _herm(A).dot else: XH_dot = XH_mat = A.dot X_dot = X_matmat = _herm(A).dot def matvec_XH_X(x): return XH_dot(X_dot(x)) def matmat_XH_X(x): return XH_mat(X_matmat(x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=A.dtype, matmat=matmat_XH_X, shape=(min(A.shape), min(A.shape))) eigvals, eigvec = eigsh(XH_X, k=self.k, tol=self.tol ** 2, maxiter=self.maxiter, ncv=self.ncv, which=self.which, v0=self.v0) eigvals = np.maximum(eigvals.real, 0) t = eigvec.dtype.char.lower() factor = {'f': 1E3, 'd': 1E6} cond = factor[t] * np.finfo(t).eps cutoff = cond * np.max(eigvals) above_cutoff = (eigvals > cutoff) nlarge = above_cutoff.sum() nsmall = self.k - nlarge slarge = np.sqrt(eigvals[above_cutoff]) s = np.zeros_like(eigvals) s[:nlarge] = slarge if not self.return_singular_vectors: return np.sort(s) if n > m: vlarge = eigvec[:, above_cutoff] ularge = X_matmat(vlarge) / slarge if self.return_singular_vectors != 'vh' else None vhlarge = _herm(vlarge) else: ularge = eigvec[:, above_cutoff] vhlarge = _herm(X_matmat(ularge) / slarge) if self.return_singular_vectors != 'u' else None u = _augmented_orthonormal_cols(ularge, nsmall) if ularge is not None else None vh = _augmented_orthonormal_rows(vhlarge, nsmall) if vhlarge is not None else None indexes_sorted = np.argsort(s) s = s[indexes_sorted] if u is not None: u = u[:, indexes_sorted] if vh is not None: vh = vh[indexes_sorted] return u, s, vh def _augmented_orthonormal_cols(U, n): if U.shape[0] <= n: return U Q, R = np.linalg.qr(U) return Q[:, :n] def _augmented_orthonormal_rows(V, n): if V.shape[1] <= n: return V Q, R = np.linalg.qr(V.T) return Q[:, :n].T def _herm(x): return np.conjugate(x.T)这段代码中使用的scipy包太旧了,导致会出现报错信息为:cannot import name 'is_pydata_spmatrix' from 'scipy.sparse' (D:\Anaconda\lib\site-packages\scipy\sparse_init.py),将这段代码修改为使用最新版的scipy包

好的,将使用最新版的scipy包进行修改。首先需要将代码中的`is_pydata_spmatrix`替换为`isspmatrix_csr`。同时需要将代码开头的导入语句修改为`from scipy.sparse.linalg import eigsh, LinearOperator from scipy.sparse import isspmatrix_csr`。

class MyDense(keras.layers.Layer): def __init__(self, units, activation=None, **kwargs): super().__init__(**kwargs) self.units = units self.activation = keras.activations.get(activation) def build(self, batch_input_shape): self.kernel = self.add_weight( name="kernel", shape=[batch_input_shape[-1], self.units], initializer="glorot_normal") self.bias = self.add_weight( name="bias", shape=[self.units], initializer="zeros") super().build(batch_input_shape) # must be at the end def call(self, X): return self.activation(X @ self.kernel + self.bias) def compute_output_shape(self, batch_input_shape): return tf.TensorShape(batch_input_shape.as_list()[:-1] + [self.units]) def get_config(self): base_config = super().get_config() return {**base_config, "units": self.units, "activation": keras.activations.serialize(self.activation)}

这段代码定义了一个自定义的Keras层,名为MyDense。该层继承了Keras的Layer类,重写了__init__、build、call等方法。 在__init__方法中,定义了该层的参数units(输出维度)和激活函数activation,同时调用了父类的__init__方法。 在build方法中,定义了该层的权重kernel和偏置bias,权重的初始化方式为glorot_normal,偏置的初始化方式为zeros。同时调用了父类的build方法。 在call方法中,实现了该层的前向传播,即输入X与权重kernel相乘并加上偏置bias,再通过激活函数activation进行激活得到输出。 在compute_output_shape方法中,返回该层的输出shape。 在get_config方法中,返回该层的配置信息,包括units和activation等参数。

相关推荐

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

能给一个完整的实例吗,比方说以下python代码:import cv2 import numpy as np # 加载图像 image = cv2.imread("/root/camera/test/v4l2_cap.jpg") # 查看图像中是否存在蓝色和红色 blue_pixels = np.sum(image[:, :, 0]) # 蓝色通道 red_pixels = np.sum(image[:, :, 2]) # 红色通道 colors = "0" if blue_pixels > red_pixels: color = "Blue" elif blue_pixels < red_pixels: color = "Red" else: color = "None" # 将图像转换为灰度图像 gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 边缘增强 enhanced_image = cv2.Canny(gray_image, 33, 45) # 形态学操作(腐蚀和膨胀) kernel = np.ones((3, 3), np.uint8) edges1 = cv2.dilate(enhanced_image, kernel, iterations=3) # 在灰度图像中检测圆形 circles = cv2.HoughCircles(edges1, cv2.HOUGH_GRADIENT, dp=1, minDist=100, param1=66, param2=25, minRadius=90, maxRadius=185) shape="" if circles is not None: # 在原始图像上绘制检测到的圆 circles = np.uint16(np.around(circles)) for circle in circles[0, :]: x, y, radius = circle[0], circle[1], circle[2] if abs(x - image.shape[1] // 2) > 100: continue shape = "Circle" cv2.circle(image, (x, y), 90, (0, 255, 0), 2) cv2.circle(image, (x, y), 2, (0, 0, 255), 3) else: shape = "None" # 判断是否同时出现 Rectangle 和 Triangle以及颜色是否有红,绿 if color == "Red" and shape != "Circle" : result = 'r' elif color == "Blue" and shape == "Circle" : result = 'b' else: result = 'n' # 打印检测到的形状、颜色 #print(f"Color:{color}") #print(f"shape:{shape}") print(f"Result: {result}") #cv2.imshow("enhanced_image", enhanced_image) #cv2.imshow("edges1", edges1) #cv2.imshow("Image", image) #cv2.waitKey(0) #cv2.destroyAllWindows()

将以下代码改为C++代码: import scipy.special as sp import numpy as np import numba from numba import njit,prange import math import trimesh as tri fileName="data/blub.obj" outName='./output/blub_rec.obj' # 参数 # 限制选取球谐基函数的带宽 bw=64 # 极坐标,经度0<=theta<2*pi,纬度0<=phi<pi; # (x,y,z)=r(sin(phi)cos(theta),sin(phi)sin(theta),cos(phi)) def get_angles(x,y,z): r=np.sqrt(x*x+y*y+z*z) x/=r y/=r z/=r phi=np.arccos(z) if phi==0: theta=0 theta=np.arccos(x/np.sin(phi)) if y/np.sin(phi)<0: theta+=math.pi return [theta,phi] if __name__=='__main__': # 载入网格 mesh=tri.load(fileName) # 获得网格顶点(x,y,z)对应的(theta,phi) numV=len(mesh.vertices) angles=np.zeros([numV,2]) for i in range(len(mesh.vertices)): v=mesh.vertices[i] [angles[i,0],angles[i,1]]=get_angles(v[0],v[1],v[2]) # 求解方程:x(theta,phi)=对m,l求和 a^m_lY^m_l(theta,phi) 解出系数a^m_l # 得到每个theta,phi对应的x X,Y,Z=np.zeros([numV,1]),np.zeros([numV,1]),np.zeros([numV,1]) for i in range(len(mesh.vertices)): X[i],Y[i],Z[i]=mesh.vertices[i,0],mesh.vertices[i,1],mesh.vertices[i,2] # 求出Y^m_l(theta,phi)作为矩阵系数 sph_harm_values=np.zeros([numV,(bw+1)*(bw+1)]) for i in range(numV): for l in range(bw): for m in range(-l,l+1): sph_harm_values[i,l*(l+1)+m]=sp.sph_harm(m,l,angles[i,0],angles[i,1]) print('系数矩阵维数:{}'.format(sph_harm_values.shape)) # 求解方程组,得到球谐分解系数 a_x=np.linalg.lstsq(sph_harm_values,X,rcond=None)[0] a_y=np.linalg.lstsq(sph_harm_values,Y,rcond=None)[0] a_z=np.linalg.lstsq(sph_harm_values,Z,rcond=None)[0] # 从系数恢复的x,y,z坐标,存为新的点云用于比较 x=np.matmul(sph_harm_values,a_x) y=np.matmul(sph_harm_values,a_y) z=np.matmul(sph_harm_values,a_z) with open(outName,'w') as output: for i in range(len(x)): output.write("v %f %f %f\n"%(x[i,0],y[i,0],z[i,0]))

import numpy as np from sklearn import datasets from sklearn.linear_model import LinearRegression np.random.seed(10) class Newton(object): def init(self,epochs=50): self.W = None self.epochs = epochs def get_loss(self, X, y, W,b): """ 计算损失 0.5sum(y_pred-y)^2 input: X(2 dim np.array):特征 y(1 dim np.array):标签 W(2 dim np.array):线性回归模型权重矩阵 output:损失函数值 """ #print(np.dot(X,W)) loss = 0.5np.sum((y - np.dot(X,W)-b)2) return loss def first_derivative(self,X,y): """ 计算一阶导数g = (y_pred - y)*x input: X(2 dim np.array):特征 y(1 dim np.array):标签 W(2 dim np.array):线性回归模型权重矩阵 output:损失函数值 """ y_pred = np.dot(X,self.W) + self.b g = np.dot(X.T, np.array(y_pred - y)) g_b = np.mean(y_pred-y) return g,g_b def second_derivative(self,X,y): """ 计算二阶导数 Hij = sum(X.T[i]X.T[j]) input: X(2 dim np.array):特征 y(1 dim np.array):标签 output:损失函数值 """ H = np.zeros(shape=(X.shape[1],X.shape[1])) H = np.dot(X.T, X) H_b = 1 return H, H_b def fit(self, X, y): """ 线性回归 y = WX + b拟合,牛顿法求解 input: X(2 dim np.array):特征 y(1 dim np.array):标签 output:拟合的线性回归 """ self.W = np.random.normal(size=(X.shape[1])) self.b = 0 for epoch in range(self.epochs): g,g_b = self.first_derivative(X,y) # 一阶导数 H,H_b = self.second_derivative(X,y) # 二阶导数 self.W = self.W - np.dot(np.linalg.pinv(H),g) self.b = self.b - 1/H_bg_b print("itration:{} ".format(epoch), "loss:{:.4f}".format( self.get_loss(X, y , self.W,self.b))) def predict(): """ 需要自己实现的代码 """ pass def normalize(x): return (x - np.min(x))/(np.max(x) - np.min(x)) if name == "main": np.random.seed(2) X = np.random.rand(100,5) y = np.sum(X3 + X**2,axis=1) print(X.shape, y.shape) # 归一化 X_norm = normalize(X) X_train = X_norm[:int(len(X_norm)*0.8)] X_test = X_norm[int(len(X_norm)*0.8):] y_train = y[:int(len(X_norm)0.8)] y_test = y[int(len(X_norm)0.8):] # 牛顿法求解回归问题 newton=Newton() newton.fit(X_train, y_train) y_pred = newton.predict(X_test,y_test) print(0.5np.sum((y_test - y_pred)**2)) reg = LinearRegression().fit(X_train, y_train) y_pred = reg.predict(X_test) print(0.5np.sum((y_test - y_pred)**2)) ——修改代码中的问题,并补全缺失的代码,实现牛顿最优化算法

解释代码:def main(args): obj_names = np.loadtxt(args.obj_file, dtype=str) N_map = np.load(args.N_map_file) mask = cv2.imread(args.mask_file, 0) N = N_map[mask > 0] L = np.loadtxt(args.L_file) if args.stokes_file is None: stokes = np.tile(np.array([[1, 0, 0, 0]]), (len(L), 1)) else: stokes = np.loadtxt(args.stokes_file) v = np.array([0., 0., 1.], dtype=float) H = (L + v) / np.linalg.norm(L + v, axis=1, keepdims=True) theta_d = np.arccos(np.sum(L * H, axis=1)) norm = np.linalg.norm(L - H, axis=1, keepdims=True) norm[norm == 0] = 1 Q = (L - H) / norm for i_obj, obj_name in enumerate(obj_names[args.obj_range[0]:args.obj_range[1]]): print('===== {} - {} start ====='.format(i_obj, obj_name)) obj_name = str(obj_name) pbrdf = PBRDF(os.path.join(args.pbrdf_dir, obj_name + 'matlab', obj_name + 'pbrdf.mat')) ret = Parallel(n_jobs=args.n_jobs, verbose=5, prefer='threads')([delayed(render)(i, pbrdf, n, L, stokes, H, theta_d, Q) for i, n in enumerate(N)]) ret.sort(key=lambda x: x[0]) M = np.array([x[1] for x in ret], dtype=float) if args.save_type != 'raw': M = M / M.max() pimgs = np.zeros((len(L), 4) + N_map.shape) pimgs[:, :, mask > 0] = M.transpose(2, 1, 0, 3) out_path = os.path.join(args.out_dir, obj_name) makedirs(out_path) print('Saving images...') fnames = [] for i, imgs in enumerate(tqdm(pimgs)): if args.save_type == 'npy' or args.save_type == 'raw': for img, pangle in zip(imgs, pangles): fname = '{:03d}{:03d}.npy'.format(i + 1, pangle) fnames.append(fname) np.save(os.path.join(out_path, fname), img) elif args.save_type == 'png': for img, pangle in zip(imgs, pangles): fname = '{:03d}{:03d}.png'.format(i + 1, pangle) fnames.append(fname) img = img * np.iinfo(np.uint16).max img = img[..., ::-1] cv2.imwrite(os.path.join(out_path, fname), img.astype(np.uint16)) np.save(os.path.join(out_path, 'normal_gt.npy'), N_map) shutil.copyfile(args.mask_file, os.path.join(out_path, 'mask.png')) shutil.copyfile(args.L_file, os.path.join(out_path, 'light_directions.txt')) print('===== {} - {} done ====='.format(i_obj, obj_name))

import cv2 import numpy as np # 提取图像的HOG特征 def get_hog_features(image): hog = cv2.HOGDescriptor() hog_features = hog.compute(image) return hog_features # 加载训练数据集 train_data = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128"] train_labels = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128\labels.txt"] for i in range(num_samples): image = cv2.imread('image_'+str(i)+'.jpg', 0) hog_features = get_hog_features(image) hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) color_hist = cv2.calcHist([hsv_image], [0, 1], None, [180, 256], [0, 180, 0, 256]) color_features = cv2.normalize(color_hist, color_hist).flatten() train_data.append(hog_features) train_labels.append(labels[i]) # 训练SVM模型 svm = cv2.ml.SVM_create() svm.setType(cv2.ml.SVM_C_SVC) svm.setKernel(cv2.ml.SVM_LINEAR) svm.train(np.array(train_data), cv2.ml.ROW_SAMPLE, np.array(train_labels)) # 对测试图像进行分类 test_image = cv2.imread('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\maskslic2_roi.png', 0) test_features = get_hog_features(test_image) result = svm.predict(test_features.reshape(1,-1)) # 显示分割结果 result_image = np.zeros(test_image.shape, np.uint8) for i in range(test_image.shape[0]): for j in range(test_image.shape[1]): if result[i,j] == 1: result_image[i,j] = 255 cv2.imshow('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\Result.png', result_image) cv2.waitKey(0) cv2.destroyAllWindows()

def MEAN_Spot(opt): # channel 1 inputs1 = layers.Input(shape=(42,42,1)) conv1 = layers.Conv2D(3, (5,5), padding='same', activation='relu', kernel_regularizer=l2(0.001))(inputs1) bn1 = layers.BatchNormalization()(conv1) pool1 = layers.MaxPooling2D(pool_size=(3, 3), padding='same', strides=(3,3))(bn1) do1 = layers.Dropout(0.3)(pool1) # channel 2 inputs2 = layers.Input(shape=(42,42,1)) conv2 = layers.Conv2D(3, (5,5), padding='same', activation='relu', kernel_regularizer=l2(0.001))(inputs2) bn2 = layers.BatchNormalization()(conv2) pool2 = layers.MaxPooling2D(pool_size=(3, 3), padding='same', strides=(3,3))(bn2) do2 = layers.Dropout(0.3)(pool2) # channel 3 inputs3 = layers.Input(shape=(42,42,1)) conv3 = layers.Conv2D(8, (5,5), padding='same', activation='relu', kernel_regularizer=l2(0.001))(inputs3) bn3 = layers.BatchNormalization()(conv3) pool3 = layers.MaxPooling2D(pool_size=(3, 3), padding='same', strides=(3,3))(bn3) do3 = layers.Dropout(0.3)(pool3) # merge 1 merged = layers.Concatenate()([do1, do2, do3]) # interpretation 1 merged_conv = layers.Conv2D(8, (5,5), padding='same', activation='relu', kernel_regularizer=l2(0.1))(merged) merged_pool = layers.MaxPooling2D(pool_size=(2, 2), padding='same', strides=(2,2))(merged_conv) flat = layers.Flatten()(merged_pool) flat_do = layers.Dropout(0.2)(flat) # outputs outputs = layers.Dense(1, activation='linear', name='spot')(flat_do) #Takes input u, v, os model = keras.models.Model(inputs=[inputs1, inputs2, inputs3], outputs=[outputs]) model.compile( loss={'spot':'mse'}, optimizer=opt, metrics={'spot':tf.keras.metrics.MeanAbsoluteError()}, ) return model 如何引入CBAM-ResNet

import os import cv2 import numpy as np def gabor_kernel(ksize, sigma, gamma, lamda, alpha, psi): """ reference https://en.wikipedia.org/wiki/Gabor_filter """ sigma_x = sigma sigma_y = sigma / gamma ymax = xmax = ksize // 2 # 9//2 xmin, ymin = -xmax, -ymax # print("xmin, ymin,xmin, ymin",xmin, ymin,ymax ,xmax) # X(第一个参数,横轴)的每一列一样, Y(第二个参数,纵轴)的每一行都一样 (y, x) = np.meshgrid(np.arange(ymin, ymax + 1), np.arange(xmin, xmax + 1)) # 生成网格点坐标矩阵 # print("y\n",y) # print("x\n",x) x_alpha = x * np.cos(alpha) + y * np.sin(alpha) y_alpha = -x * np.sin(alpha) + y * np.cos(alpha) print("x_alpha[0][0]", x_alpha[0][0], y_alpha[0][0]) exponent = np.exp(-.5 * (x_alpha ** 2 / sigma_x ** 2 + y_alpha ** 2 / sigma_y ** 2)) # print(exponent[0][0]) # print(x[0],y[0]) kernel = exponent * np.cos(2 * np.pi / lamda * x_alpha + psi) print(kernel) # print(kernel[0][0]) return kernel def gabor_filter(gray_img, ksize, sigma, gamma, lamda, psi): filters = [] for alpha in np.arange(0, np.pi, np.pi / 4): print("alpha", alpha) kern = gabor_kernel(ksize=ksize, sigma=sigma, gamma=gamma, lamda=lamda, alpha=alpha, psi=psi) filters.append(kern) gabor_img = np.zeros(gray_img.shape, dtype=np.uint8) i = 0 for kern in filters: fimg = cv2.filter2D(gray_img, ddepth=cv2.CV_8U, kernel=kern) gabor_img = cv2.max(gabor_img, fimg) i += 1 p = 1.25 gabor_img = (gabor_img - np.min(gabor_img, axis=None)) ** p _max = np.max(gabor_img, axis=None) gabor_img = gabor_img / _max print(gabor_img) gabor_img = gabor_img * 255 return gabor_img.astype(dtype=np.uint8) def main(): dir_path = '7/' files = os.listdir(dir_path) for i in files: print(i) img = cv2.imread(dir_path + "/" + i) img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gabor_img = gabor_filter(img_gray, ksize=9, sigma=1, gamma=0.5, lamda=5, psi=-np.pi / 2) Img_Name = "5/gabor/" + str(i) cv2.imwrite(Img_Name, gabor_img) main()

最新推荐

recommend-type

zigbee-cluster-library-specification

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

管理建模和仿真的文件

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

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解答下列问题:S—>S;T|T;T—>a 构造任意项目集规范族,构造LR(0)分析表,并分析a;a

对于这个文法,我们可以构造以下项目集规范族: I0: S -> .S S -> .T T -> .a I1: S -> S. [$ T -> T. [$ I2: S -> T. I3: S -> S.;S S -> S.;T T -> T.;a 其中,点(.)表示已经被扫描过的符号,;$表示输入串的结束符号。 根据项目集规范族,我们可以构造出LR(0)分析表: 状态 | a | $ ---- | - | - I0 | s3| I1 | |acc I2 | | 其中s3表示移进到状态3,acc表示接受。在分析字符串a;a时,我们可以按照以下步骤进行
recommend-type

JSBSim Reference Manual

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

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

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

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

mac上和window原生一样的历史剪切板工具有什么

好的,我明白了您的要求。关于您的问题,为使Mac与Windows的历史剪切板功能类似,可以使用第三方工具"CopyClip"、"Alfred"、"Clipboard Manager"等。这些工具可以记录您复制到剪切板的所有内容,而不仅仅是最后一次复制。同时,它们还可以进行搜索和过滤,以便您更快地找到需要的内容。希望这能回答您的问题。
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。
recommend-type

关系数据表示学习

关系数据卢多维奇·多斯桑托斯引用此版本:卢多维奇·多斯桑托斯。关系数据的表示学习机器学习[cs.LG]。皮埃尔和玛丽·居里大学-巴黎第六大学,2017年。英语。NNT:2017PA066480。电话:01803188HAL ID:电话:01803188https://theses.hal.science/tel-01803188提交日期:2018年HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaireUNIVERSITY PIERRE和 MARIE CURIE计算机科学、电信和电子学博士学院(巴黎)巴黎6号计算机科学实验室D八角形T HESIS关系数据表示学习作者:Ludovic DOS SAntos主管:Patrick GALLINARI联合主管:本杰明·P·伊沃瓦斯基为满足计算机科学博士学位的要求而提交的论文评审团成员:先生蒂埃里·A·退休记者先生尤尼斯·B·恩