Opencv-python 特征矩阵与图片分类

原始图片
在这里插入图片描述

import cv2 as cv
import matplotlib.pyplot as mp

# 1.读取图片
original = cv.imread("./table.jpg")
gray = cv.cvtColor(original, cv.COLOR_BGR2GRAY)

# 2.图片特征处理
sift = cv.xfeatures2d.SIFT_create()
keypoints = sift.detect(gray)

# 3.提取特征值矩阵
_, desc = sift.compute(gray, keypoints)
print(desc.shape)

# 4.显示特征矩阵
mp.imshow(desc.T, cmap="gist_rainbow")
mp.show()

特征矩阵图片
在这里插入图片描述
图片分类
文件下载地址
链接: https://pan.baidu.com/s/1-pDDyJqXkpXExUfV0O0l5A 提取码: t2bb

"""
    图片分类
"""
import numpy as np
import cv2 as cv
import python_speech_features as sf
import sklearn.svm as svm
import sklearn.metrics as sm
import sklearn.preprocessing as sp
import os


# 图片文件路径
def search_files(directory):
    """
        检索目录下的所有wav文件 返回目录字典
        {“appple”:[url, url...],
        “kiwi”:[url, url...],....}
    """
    object = {}
    for curdir, subdirs, files in os.walk(directory):
        for file in files:
            if file.endswith(".jpg"):
                label = curdir.split(os.path.sep)[-1]
                if label not in object:
                    object[label] = []
                url = os.path.join(curdir, file)
                object[label].append(url)
    return object


# 训练集 图片路径
train_urls = search_files("./objects/training")
print(train_urls)

# 整理训练集
train_x, train_y = [], []
for label, urls in train_urls.items():
    for file in urls:
        # 提取图片的特征值样本
        image = cv.imread(file)
        gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
        h, w = gray.shape
        f = 200 / min(h, w)  # 计算伸缩比例
        gray = cv.resize(gray, None, fx=f, fy=f)
        shift = cv.xfeatures2d.SIFT_create()
        keypoints = shift.detect(gray)
        _, desc = shift.compute(gray, keypoints)
        # desc (None, 128)
        sample = np.mean(desc, axis=0)
        train_x.append(sample)
        train_y.append(label)

train_x = np.array(train_x)

# 训练集 Y标签编码
encoder = sp.LabelEncoder()
train_y_label = encoder.fit_transform(train_y)
print(train_x.shape, train_y_label.shape)

# 建立SVC模型 并训练模型
model = svm.SVC(kernel="poly", degree=2, gamma="auto", probability=True)
model.fit(train_x, train_y_label)
prd_train_y = model.predict(train_x)
print(sm.classification_report(train_y_label, prd_train_y))

# 加载测试集
test_urls = search_files("./objects/testing")
print(test_urls)

# 测试集数据整理
test_x, test_y = [], []
for label, urls in test_urls.items():
    for file in urls:
        image = cv.imread(file)
        gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
        h, w = gray.shape
        f = 200 / min(h, w)  # 计算伸缩比例
        gray = cv.resize(gray, None, fx=f, fy=f)
        shift = cv.xfeatures2d.SIFT_create()
        keypoints = shift.detect(gray)
        _, desc = shift.compute(gray, keypoints)
        # desc (None, 128)
        sample = np.mean(desc, axis=0)
        test_x.append(sample)
        test_y.append(label)

# 标签编码
test_x = np.array(test_x)
test_y_label = encoder.transform(test_y)

# 使用模型预测数据
prd_test_y = model.predict(test_x)
print(sm.classification_report(test_y_label, prd_test_y))

# 输出置信概率
probs = model.predict_proba(test_x)
print(np.round(probs, 3))

# 输出结果
for label, prob in zip(encoder.inverse_transform(prd_test_y), probs.max(axis=1)):
    print(label, np.round(prob, 3))

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

廷益--飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值