今天主要想说的是,分形中的差分盒子维数的原理,基于分形的基础概念就不在这里说啦.

分形维数可以用于定量描述图像表面的空间复杂程度,能够定量的表现图像的纹理特征. 采用不同的维数进行纹理特征描述时,精度有所区别,我们今天主要来说一下比较简单的盒子维.


1.差分盒子维数

Gangepain 和 Roques-Carms 在1986年提出基于盒计数(Box-counting)的分形维数,通过计算覆盖图像表面的最小盒子数来度量.

说得详细一点:将一幅大小为

的图像分为
的子块,图像
处的灰度值为
,总的灰度级为
. 此时将图像看成三维物体的表面灰度集
.
平面上是
的网格,
轴为网格内像素灰度值,每个网格上有若干个盒子叠加,盒子高度为
.
注:一般灰度图像的灰度级为 L = 256.

若在第

个网格中,第
个盒子中包含网格内灰度最小值,第
个盒子包含网格内灰度最大值,则覆盖第
个网格的盒子数
.

覆盖整个盒子的数为

为:

由此可求分形维数D为:

式中:

.

通过改变网格

的大小计算一组
,然后计算点对
的线性回归,其斜率即是分形维数
.

2.实验

我们先来看一下,将灰度图像看作三维物体的表面灰度集是怎么样呢?

① 实现灰度图像的表面灰度集,采用matlab程序,如下:

function Show_GraySurface(filename)%   把一幅图像看成三维空间的曲面,
%   像素的位置(x,y)构成xoy坐标面,
%   像素的灰度值看成z轴的值由此构成灰度曲面picture_dir = 'D:Matlabworktest';I = imread([picture_dir,filename]);if (length(size(I)) > 2)I = rgb2gray(I);end M = size(I,1);Temp = diag(1:256)*ones(256,256);x = reshape(Temp.',1,M*M);y = reshape(Temp,1,M*M);z = reshape(I,1,M*M);tri = delaunay(x,y);trisurf(tri,x,y,z);shading interpview(3);grid on;colorbarend

附加:python程序

import cv2
import numpy as np
import matplotlib.pyplot as pltdef surface(img):X = np.arange(0, 363, 1) # cols of the imageY = np.arange(0, 480, 1) # rows of the imageX,Y = np.meshgrid(X,Y)   # extending pointsZ = np.array(img)      #2 dimensionfig, ax = plt.subplots(subplot_kw = {"projection": "3d"})surf = ax.plot_surface(X, Y, Z, cmap = "rainbow", linewidth = 0, antialiased = False)ax.contour(X, Y, Z, zdir = 'z', offset = 75, cmap = plt.get_cmap('rainbow'))  # projectionfig.colorbar(surf)  # colorbarplt.show()if __name__ == "__main__":img = cv2.imread("3.jpg", 0)surface(img)

注:matlab程序中,图像大小256 x 256.

效果如下:

图1 图像灰度曲面

② 计算差分盒维数,采用Python程序.

★ 主程序文件:main.py

import cv2
from DBC import Fractalsrc = cv2.imread("D5.jpg", cv2.IMREAD_UNCHANGED)# create an object
obj = Fractal()#linear fitting for solveing differential box dimension(DBC)
obj.execute(src)

★ 子程序文件:DBC.py

import numpy as np
import cv2
import math
from matplotlib import pyplot as pltclass Fractal():def __init__(self):pass# method of image grayingdef gray(self, src):gray_img = np.uint8(src[:,:, 0] * 0.144 + src[:, :, 1] * 0.587 + src[:, :, 2] * 0.299)    # cla_img = cv2.bilateralFilter(gray_img, 3, 64, 64)# #clahe processing# clahe = cv2.createCLAHE(clipLimit = 3, tileGridSize = (32, 32))# cla_img = clahe.apply(bil_img)return gray_img#  differential box dimension counting (DBC)def differential_box_counting (self, gray_img):h, w = gray_img.shape[:2]M = min(h,w)Nr = []for s in range(2,M//2+1,1):         # the box side length: 2 ~ M//2H = 255*s/M                     # high of the boxbox_num = 0                     # initialization of the box numberfor row in range(h//s):         # h//s: the number of rows in the box;  w//s: the number of columns in the boxfor col in range(w//s):nr = math.ceil((np.max(gray_img[row*s:(row+1)*s, col*s:(col+1)*s])-np.min(gray_img[row*s:(row+1)*s, col*s:(col+1)*s]))/H +1)box_num += nrNr.append(box_num)return Nr,Mdef least_squares(self, x , y):"""(1) input datesets of x and y (2) the straight line is fitted by Least-square method(3) output a coefficient(w), intercept(b) and coefficient of determination (r)(4) the fitting straight line : y = wx + b"""x_ = x.mean()y_ = y.mean()m1 = np.zeros(1)m2 = np.zeros(1)m3 = np.zeros(1)  k1 = np.zeros(1)k2 = np.zeros(1)k3 = np.zeros(1)for i in np.arange(len(x)):m1 += (x[i] - x_)* y[i]m2 += np.square(x[i])m3 += x[i]k1 += (x[i]-x_) * (y[i]-y_)k2 += np.square(x[i] - x_)k3 += np.square(y[i] - y_)w = m1/(m2 - 1/len(x) * np.square(m3))b = y_ - w * x_r = k1 / np.sqrt(k2 * k3)return w, b, rdef plot_line(self, x, y, w, b, r):# print(w, b, r ** 2)y_pred = w * x + b# create a fig and an axesfig, ax = plt.subplots(figsize = (10, 5))# fontsyle: SimHei(黑体),support chineseplt.rcParams['font.sans-serif'] = ['SimHei']ax.plot(x, y, 'co', markersize = 6, label = 'scatter datas')ax.plot(x, y_pred, 'r-', linewidth = 2, label = 'y = %.4fx + %.4f' %(w, b))# set xlim and yxlim ax.set_aspect("0.5")ax.set_xlim(1, 6)ax.set_ylim(2, 12)# set x_ticks and y_ticksax.tick_params(labelsize = 16)labels = ax.get_xticklabels() + ax.get_yticklabels()[label.set_fontname('Times New Roman') for label in labels] # create gridsax.grid(which = "major", axis = "both")# display labelsfont1 = {'family': 'Times New Roman', 'weight': 'normal', 'size': 16}ax.legend(prop = font1) #set x_label and y_labelfont2 = {'family': 'Times New Roman', 'weight': 'normal', 'size': 20}ax.set_xlabel("ln 1/r", fontdict = font2)ax.set_ylabel("ln Nr", fontdict = font2)# set a position of "R^2"ax.text(3.5, 7.8, 'R^2 = %.4f' % float(r * r), fontdict = font1,verticalalignment='center', horizontalalignment ='left', rotation=0)plt.savefig("line.jpg", dpi = 300, bbox_inches = "tight")plt.show()def execute(self, img):gray_img = self.gray(img)Nr, M = self.differential_box_counting(gray_img)x = np.log([round(M/s) for s in range(2,M//2+1,1)])y = np.log(Nr)#fitting a straight linew, b, r = self.least_squares(x, y)self.plot_line(x, y, w, b, r)

我们来看一下效果图:用最小二乘法进行拟合,斜率就是我们需要的维数.

图2 线性拟合
# 其实最小二乘法,也可以通过sklearn库直接调用.import cv2
import numpy as np
import math
from matplotlib import pyplot as plt
from sklearn import linear_model
from sklearn.metrics import r2_scorefrom numba import jit@jit
def differential_box_counting (gray_img):# cv2.imshow("gray_img",gray_img)h, w = gray_img.shape[:2]M = min(h,w)Nr = []for s in range(2,M//2+1,1):         #盒子边长从2到图片最小尺寸的二分之一,每次边长加1H = 255*s/M        #盒子柱高lbox_num = 0         #初始化盒子数for row in range(h//s):           #(h//s)为盒子的行数,(w//s)为盒子的列数for col in range(w//s):nr = math.ceil((np.max(gray_img[row*s:(row+1)*s, col*s:(col+1)*s])-np.min(gray_img[row*s:(row+1)*s, col*s:(col+1)*s]))/H +1)box_num += nrNr.append(box_num)return Nr,Mdef Least_squares():x = np.log([round(M/s) for s in range(2,M//2+1,1)])x = np.array(x).reshape((-1, 1))  # transform list to numpy.ndarrayy = np.log(Nr)y = np.array(y).reshape((-1, 1))  # transform list to numpy.ndarray# Create linear regression objectregr = linear_model.LinearRegression()  # is equivalent to  # regr = linear_model.Ridge(alpha = 0)# Train the model using the setsregr.fit(x, y)y_pred = regr.predict(x)# The coefficientsprint('Coefficients:   ', regr.coef_)#The interceptprint('Intercept:  ', regr.intercept_)# The coefficient of determination: 1 is perfect predictionprint('Coefficient of determination: %.8f'% r2_score(y, y_pred))plt.scatter(x, y,  color='black')plt.plot(x, y_pred, color='blue', linewidth=3)plt.show()if __name__ == "__main__":gray_img = cv2.imread("D3.jpg", cv2.IMREAD_GRAYSCALE)# thresh = cv2.threshold(gray_img, 220, 255, cv2.THRESH_BINARY)[1]Nr,M = differential_box_counting(gray_img)Least_squares()

喜欢的话,给予鼓励,点个赞...

matlab盒子分形维数_分形:盒子维数相关推荐

  1. matlab盒子分形维数_分形维数--matlab

    一维曲线分形维数的 matlab 程序 function D=FractalDim(y,cellmax) % 求输入一维信号的计盒分形维数 %y 是一维信号 %cellmax: 方格子的最大边长 , ...

  2. matlab求向量空间的基,线性空间维数与基的求法.doc

    线性空间维数与基的求法,求子空间的基和维数,线性空间的维数,线性空间维数,向量空间的基与维数,什么叫线性的维数和秩,matlab求矩阵的维数,matlab求矩阵维数,基和维数,cao法求嵌入维数 线性 ...

  3. android 平板投影电视盒子,《家庭影院》将手机/平板/PC全部投影到盒子(电视)_小米盒子论坛...

    小米盒子到手,小米盒子本身通过远程安装等方式安装很多视频软件,但是按照广电局的最新发文,估计今后盒子视频软件要被清洗,所以教大家一个方法,将手机/平板/电脑上的视频投影到电视上(借助小米盒子),这样就 ...

  4. CSS基础学习-8.CSS盒子模型_标准盒子9.CSS怪异盒子

    怪异盒模型 box-sizing:content-box;/*正常盒模型,默认值*/ box-sizing:border-box:/*怪异盒模型,固定了盒子的大小,无论是否添加内边距还是边框,盒子的大 ...

  5. Java幸运盒子代码_幸运盒子扭蛋机小程序app开发

    互联网产品是植根于互联网大环境的产品,幸运盒子扭蛋机小程序app开发是互联网产品的基本生长土壤.互联网的思想.原则和方法,必然以类似于"基因"继承的形式在每一个具体互联网产品中得以 ...

  6. matlab实现粗糙表面_基于分形理论的球头铣削表面形貌研究

    分形理论作为一种非线性科学前沿理论,最早由美国科学家曼德布罗特(Mandelbrot)提出,被用于研究复杂的.不规则的几何形态.分形表面具有自相似性和尺度不变形两个特征.随着研究的深入,Thomas ...

  7. sierpinski三角形的维数_谢宾斯基三角形的几种生成方法

    简介 谢宾斯基三角形(Sierpinski triangle)是一种分形,由波兰数学家谢宾斯基在1915年提出.它是一种自相似集. 几种生成方法 方法一:去掉中心 取一个实心的三角形(多数用等边三角形 ...

  8. 华为盒子在烧写过程中不显示进度条原因_电视盒子排行榜,销量前三的小米、华为、泰捷谁更值得买?...

    原标题:电视盒子排行榜,销量前三的小米.华为.泰捷谁更值得买? 智能电视和电视盒子现如今已是家家户户都普及的电子产品了,但和智能手机.电脑一样,都面临着长期使用卡顿死机频的情况,如何选择一款系统流畅发 ...

  9. matlab中维数的理解

    a = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 就上面这样一个矩阵而言,它有3行5列 第一维:行维,即行向,也即垂直方向,维数为3,就矩阵a而言 第二维:列维,即列向,也即水平方向 ...

最新文章

  1. Topcoder SRM 663 DIV 1
  2. VTK:标记网格用法实战
  3. 【OpenCV归纳】4 关于HighGUI
  4. Nginx的应用之虚拟主机
  5. Maven学习总结(44)——Maven构建时生命周期及其常用集成命令详解
  6. 如何高效阅读 Spark 和 Hadoop 这类大型开源项目源代码?
  7. android 关闭服务代码,android – 调用stopService方法时,服务不会停止
  8. 第26讲 js函数调用过程内存分析 js函数细节
  9. μc/os-II原理简介(笔记)
  10. java 反译md5加密_Java MD5加密与反编译
  11. 应用comsol模拟水力压裂应力分布
  12. Mybatis的缓存
  13. Stochastic Weight Averaging (SWA) 随机权重平均
  14. java 基础知识学习2
  15. c语言用二维数组查找负数,[抄道题] 在二维数组中找某数
  16. metasploit简单使用:复现永恒之蓝
  17. ipados 文件 连接服务器,如何管理iPad文件 iPadOS14使用教程
  18. c语言过去硬盘序列号,[C]获取硬盘序列号
  19. css中的选择器及其权重
  20. 向虚拟机中传输文件的新解法——高效有用的邮箱传输

热门文章

  1. P6329 【模板】点分树 | 震波
  2. Libre OJ 「BalticOI 2013」非回文数 数位dp
  3. CF1473E Minimum Path(拆点+最短路)
  4. 2021牛客NOIP提高组第二场T2——方格计数(组合数计数)
  5. 朝鲜时蔬(分数据点写算法+毒瘤数学)
  6. P4770:你的名字(SAM、线段树合并)
  7. YBTOJ洛谷P2223:软件开发(费用流)
  8. 51nod1600-Simple KMP【SAM,树链剖分】
  9. ssl初一组周六模拟赛【2018.4.7】
  10. 【模板】分散层叠算法(P6466)