CBIR

1.path.txt的建立

import os

def get_all(path):   # 递归获取指定目录下所有文件的绝对路径(非目录)

    dir_list = os.listdir(path)
    for i in dir_list:
        sub_dir = os.path.join(path, i)
        if os.path.isdir(sub_dir):
            get_all(sub_dir)
        else:   # 此时sub_dir是文件的绝对路径
            with open(r"D:\CBIR\path.txt", "a", encoding='utf-8') as f:
                f.write(sub_dir+'\n')
                f.close()            

get_all(r'D:\CBIR\101_ObjectCategories')

2.图像颜色特征

采用hsv中心矩法

https://www.cnblogs.com/bridge0904/p/13255917.html

import cv2
import numpy as np
import matplotlib.pyplot as plt
 
def color_moments(filename):
    img = cv2.imread(filename)  # 读一张彩色图片
    if img is None:
        return
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)  # RGB空间转换为HSV空间
    h, s, v = cv2.split(hsv)
    color_feature = []  # 初始化颜色特征
# 一阶矩(均值 mean)
    h_mean = np.mean(h)  # np.sum(h)/float(N)
    s_mean = np.mean(s)  # np.sum(s)/float(N)
    v_mean = np.mean(v)  # np.sum(v)/float(N)
    color_feature.extend([h_mean, s_mean, v_mean])  # 一阶矩放入特征数组
# 二阶矩 (标准差 std)
    h_std = np.std(h)  # np.sqrt(np.mean(abs(h - h.mean())**2))
    s_std = np.std(s)  # np.sqrt(np.mean(abs(s - s.mean())**2))
    v_std = np.std(v)  # np.sqrt(np.mean(abs(v - v.mean())**2))
    color_feature.extend([h_std, s_std, v_std])  # 二阶矩放入特征数组
# 三阶矩 (斜度 skewness)
    h_skewness = np.mean(abs(h - h.mean()) ** 3)
    s_skewness = np.mean(abs(s - s.mean()) ** 3)
    v_skewness = np.mean(abs(v - v.mean()) ** 3)
    h_thirdMoment = h_skewness ** (1. / 3)
    s_thirdMoment = s_skewness ** (1. / 3)
    v_thirdMoment = v_skewness ** (1. / 3)
    color_feature.extend([h_thirdMoment, s_thirdMoment, v_thirdMoment])  # 三阶矩放入特征数组

    return color_feature

a=1
for path in open(r"D:\CBIR\path.txt"):
    path = path.replace("\n", "")
    l=color_moments(path)
    with open(r"D:\CBIR\colorjuData.txt","a",encoding='utf-8') as f:
        for myline in l:
            f.write(str(myline)+',')
        f.write('\n')
        f.close()
    print(a)
    a=a+1    

采用直方图相交法

cv2.calcHist()

3.图像纹理特征

基于灰度共生矩阵提取图片的纹理特征

# -*- coding: utf-8 -*-
import cv2
import numpy as np
import math
np.set_printoptions(suppress=True)
gray_level = 16

def feature_computer(p):
    Con=0.0
    Eng=0.0
    Asm=0.0
    Idm=0.0
    for i in range(gray_level):
        for j in range(gray_level):
            Con+=(i-j)*(i-j)*p[i][j]
            Asm+=p[i][j]*p[i][j]
            Idm+=p[i][j]/(1+(i-j)*(i-j))
            if p[i][j]>0.0:
                Eng+=p[i][j]*math.log(p[i][j])
    return Asm,Con,-Eng,Idm


def glcm(arr, d_x, d_y, gray_level=16):
    '''计算并返回归一化后的灰度共生矩阵'''
    max_gray = arr.max()
    height, width = arr.shape
    arr = arr.astype(np.float64)  # 将uint8类型转换为float64,以免数据失真
    arr = arr * (gray_level - 1) // max_gray  # 若灰度级数大于gray_level,则将图像的灰度级缩小至gray_level,减小灰度共生矩阵的大小。量化后灰度值范围:0 ~ gray_level - 1
    ret = np.zeros([gray_level, gray_level])
    for j in range(height -  abs(d_y)):
        for i in range(width - abs(d_x)):  # range(width - d_x)  #注释为源代码,经评论指出错误后修改
            rows = arr[j][i].astype(int)
            cols = arr[j + d_y][i + d_x].astype(int)
            ret[rows][cols] += 1
    if d_x >= d_y:
        ret = ret / float(height * (width - 1))  # 归一化, 水平方向或垂直方向
    else:
        ret = ret / float((height - 1) * (width - 1))  # 归一化, 45度或135度方向
    return ret

if __name__=='__main__':
    num=1
    for path in open(r"D:\CBIR\path.txt"):
        path = path.replace("\n", "")
        img = cv2.imread(path)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  
        glcm_0 = glcm(img_gray, 1, 0)  #0度方向
        glcm_1 = glcm(img_gray, 0, 1)  # 45度方向
        glcm_2 = glcm(img_gray, 1, 1)  # 90度方向
        glcm_3 = glcm(img_gray, -1, 1)  # 135度方向
        asm0,con0,eng0,idm0=feature_computer(glcm_0)
        asm1,con1,eng1,idm1=feature_computer(glcm_1)
        asm2,con2,eng2,idm2=feature_computer(glcm_2)
        asm3,con3,eng3,idm3=feature_computer(glcm_3)
        asm= [asm0,asm1,asm2,asm3]
        con= [con0,con1,con2,con3]
        eng= [eng0,eng1,eng2,eng3]
        idm= [idm0,idm1,idm2,idm3]
        ava= [np.mean(asm),np.mean(con),np.mean(eng),np.mean(idm)]
        sstd= [np.std(asm),np.std(con),np.std(eng),np.std(idm)]
        with open(r"D:\CBIR\greymatrixData.txt","a",encoding='utf-8') as f:
            for i in ava:
                f.write(str(i)+",")
            for j in sstd:
                f.write(str(j)+",")
            f.write('\n')
            f.close()
        print(num)
        num=num+1
        

4.基于形状特征的搜索

形状不变矩法

#-*-coding:utf-8-*-
import cv2
from datetime import datetime
import numpy as np

def test(img):
    moments = cv2.moments(img)
    humoments = cv2.HuMoments(moments)
    humoments = np.log(np.abs(humoments)) # 同样建议取对数
    return humoments

if __name__ == '__main__':
    num=1  
    for path in open(r"D:\CBIR\path.txt"):
        path = path.replace("\n", "")
        img = cv2.imread(path)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        hum=test(img_gray)
        with open(r"D:\CBIR\ShapeNchangeData.txt","a",encoding='utf-8') as f:
            for i in hum:
                for j in i:
                    f.write(str(j)+',')
            f.write('\n')
            f.close()
        print(num)
        num=num+1

5.数据库插入数据

pathlist

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="12345678",
  database="cbir",
  auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
 
num=1
for line in open(r"D:\CBIR\path.txt"):
        line = line.replace("\n", "")
        sql = "INSERT INTO pathlist (id,path) VALUES (%s, %s)"
        val = (num, line)
        mycursor.execute(sql, val)
        mydb.commit()
        num=num+1
        print(num-1, "记录插入成功。")

color_val

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="12345678",
  database="cbir",
  auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
 
num=1
for line in open(r"D:\CBIR\color.txt"):
        line = line.replace("\n", "")
        sql = "INSERT INTO color_val (id,color) VALUES (%s, %s)"
        val = (num, line)
        mycursor.execute(sql, val)
        mydb.commit()
        num=num+1
        print(num-1, "记录插入成功。")

vein_val

import mysql.connector
 
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="12345678",
  database="cbir",
  auth_plugin='mysql_native_password'
)
mycursor = mydb.cursor()
 
num=1
for line in open(r"D:\CBIR\grey
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值