skimage 学习笔记

目录

安装:

图像分割:

裁剪图像并缩放:

彩色图像相似度:


安装:

pip install scikit-image

img_as_ubyte转为uint8格式,0-255,转为普通图像,举例:

>>> from skimage import img_as_ubyte
>>> image = np.array([0, 0.5, 1], dtype=float)
>>> img_as_ubyte(image)
WARNING:dtype_converter:Possible precision loss when converting from
float64 to uint8
array([  0, 128, 255], dtype=uint8)

图像分割:

能区分比别的地方黑的物体,但是老鼠排除不了:

import matplotlib.pyplot as plt
from skimage import io, filters

# skimage提供了io模块,顾名思义,这个模块是用来图片输入输出操作的。
img = io.imread(r"E:\new\01.jpg")

val = filters.threshold_otsu(img)
mask=(img <= val*0.9)*1.0

# io.imsave("aa.jpg",mask)
plt.figure("lena.jpg")
plt.imshow(mask)
plt.axis('off')
plt.show()

裁剪图像并缩放:

    def process(self, image, bbox):
        ''' process image with crop operation.
        Args:
            input: (h,w,3) array or str(image path). image value range:1~255.
            image_info(optional): the bounding box information of faces. if None, will use dlib to detect face.

        Returns:
            pos: the 3D position map. (256, 256, 3).
        '''
        if image.ndim < 3:
            image = np.tile(image[:, :, np.newaxis], [1, 1, 3])

        left = bbox[0]
        right = bbox[2]
        top = bbox[1]
        bottom = bbox[3]
        old_size = (right - left + bottom - top) / 2
        center = np.array([right - (right - left) / 2.0, bottom - (bottom - top) / 2.0 + old_size * 0.14])
        size = int(old_size * 1.318)

        # crop image
        src_pts = np.array([[center[0] - size / 2, center[1] - size / 2], [center[0] - size / 2, center[1] + size / 2],
                            [center[0] + size / 2, center[1] - size / 2]])
        DST_PTS = np.array([[0, 0], [0, self.resolution_inp - 1], [self.resolution_inp - 1, 0]])
        tform = estimate_transform('similarity', src_pts, DST_PTS)

彩色图像相似度:

import cv2
from skimage.metrics import structural_similarity as compare_ssim

image1 = cv2.imread(r'F:\194536.jpg')
image2 = cv2.imread(r'F:\194536.jpg')

ssim_value = compare_ssim(image1, image2, multichannel=True,channel_axis=2)

print("SSIM value:", ssim_value)

### 使用Jupyter Notebook进行深度学习猫狗图像分类大作业 #### 准备工作 为了实现基于ResNet50卷积神经网络的猫狗二分类任务,在Jupyter环境中需先安装必要的库并准备数据集。 ```bash pip install tensorflow keras matplotlib scikit-image numpy pandas h5py ``` #### 加载所需模块 在Jupyter笔记本中,首先引入所需的Python包: ```python import os from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam import matplotlib.pyplot as plt import numpy as np ``` #### 数据预处理 利用`ImageDataGenerator()`类创建用于增强训练样本多样性的图像生成器,并设置验证集的数据流[^2]。 ```python train_datagen = ImageDataGenerator( rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1./255) training_set = train_datagen.flow_from_directory('dataset/training_set', target_size=(224, 224), batch_size=32, class_mode='binary') validation_set = test_datagen.flow_from_directory('dataset/validation_set', target_size=(224, 224), batch_size=32, class_mode='binary') ``` #### 构建模型架构 导入已由ImageNet数据集预先训练好的ResNet50模型,但不包含顶层全连接层;在此基础上添加自定义输出层以适应当前的任务需求。 ```python base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) for layer in base_model.layers: layer.trainable = False x = base_model.output x = Flatten()(x) predictions = Dense(1, activation='sigmoid')(x) model = Model(inputs=base_model.input, outputs=predictions) model.compile(optimizer=Adam(), loss='binary_crossentropy', metrics=['accuracy']) ``` #### 训练过程可视化 记录每次迭代后的性能指标变化情况,便于后续分析调参效果。同时保存最佳参数配置下的模型文件。 ```python history = model.fit(training_set, epochs=25, validation_data=validation_set) plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.title('Loss Curve') plt.legend() plt.show() plt.plot(history.history['accuracy'], label='Training Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.title('Accuracy Curve') plt.legend() plt.show() ``` #### 测试与评估 选取部分测试图片展示预测类别及其置信度得分,帮助理解模型决策逻辑。此外还可以计算混淆矩阵等统计量来全面衡量泛化能力。 ```python from skimage.io import imread from skimage.transform import resize def predict_image(img_path): img = imread(img_path) img = resize(img, (224, 224)) img = np.expand_dims(img, axis=0) prediction = model.predict(preprocess_input(img))[0][0] return 'Dog' if prediction >= 0.5 else 'Cat' # Example usage of the function with a path to an image file. print(predict_image('/path/to/image.jpg')) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI算法网奇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值