matlab盒子分形维数_分形:盒子维数
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                matlab盒子分形维数_分形:盒子维数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                今天主要想說的是,分形中的差分盒子維數的原理,基于分形的基礎概念就不在這里說啦.
分形維數可以用于定量描述圖像表面的空間復雜程度,能夠定量的表現圖像的紋理特征. 采用不同的維數進行紋理特征描述時,精度有所區別,我們今天主要來說一下比較簡單的盒子維.
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盒子分形维数_分形:盒子维数的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: linux所属组权限(Linux 所属组
 - 下一篇: 安卓模拟wp系统(安卓模拟wp)