生活随笔
收集整理的這篇文章主要介紹了
SLIC超像素分割并保存分割得到的超像素块,python代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
之前做SLIC分割的過程中在網上找到的代碼都只能得到標注分割線的圖但不能得到分割后的超像素塊,所以寫了一個能夠保存分割后的超像素塊的python程序。
進行SLIC分割部分:
import skimage
from skimage
.segmentation
import slic
,mark_boundaries
from skimage
import io
import matplotlib
.pyplot
as plt
from PIL
import Image
, ImageEnhance
import numpy
as np
import cv2
path
= 'C:\\Users\\Administrator\\Desktop\\SLIC\\'
img_name
= 'test.png'
img
= io
.imread
(path
+ img_name
,as_gray
=True)
segments
= slic
(img
, n_segments
=10, compactness
=0.2,start_label
= 1)
out
=mark_boundaries
(img
,segments
)
out
= out
*255
img3
= Image
.fromarray
(np
.uint8
(out
))
img3
.show
()
seg_img_name
= 'seg.png'
img3
.save
(path
+'\\' +seg_img_name
)
對分割得到的超像素塊逐一保存
maxn
= max(segments
.reshape
(int(segments
.shape
[0]*segments
.shape
[1]),))
for i
in range(1,maxn
+1):a
= np
.array
(segments
== i
)b
= img
* aw
,h
= [],[]for x
in range(b
.shape
[0]):for y
in range(b
.shape
[1]):if b
[x
][y
] != 0:w
.append
(x
)h
.append
(y
)c
= b
[min(w
):max(w
),min(h
):max(h
)]c
= c
*255d
= c
.reshape
(c
.shape
[0],c
.shape
[1],1)e
= np
.concatenate
((d
,d
),axis
=2)e
= np
.concatenate
((e
,d
),axis
=2)'''##### 保存彩色圖片的部分,as_gray=Truea = np.array(segments == i)a = a.reshape(a.shape[0],a.shape[1],1)a1 = np.concatenate((a,a),axis=2)a = np.concatenate((a1, a), axis=2)b = img * aw,h = [],[]for x in range(b.shape[0]):for y in range(b.shape[1]):if b[x][y][0] != 0:w.append(x)h.append(y)c = b[min(w):max(w),min(h):max(h)]e = c.reshape(c.shape[0],c.shape[1],3)###################'''img2
= Image
.fromarray
(np
.uint8
(e
))img2
.save
(path
+'\\'+str(i
)+'.png')print('已保存第' + str(i
) + '張圖片')
由于超像素塊太小了不好找,做了一個在帶分割線的圖上的標記,標記值為保存下的圖片的名稱,雖然這個標記不太準但能起到輔助作用
img
= io
.imread
(path
+'\\'+seg_img_name
)for i
in range(1,maxn
+1):w
,h
= [],[]for x
in range(segments
.shape
[0]):for y
in range(segments
.shape
[1]):if segments
[x
][y
] == i
:w
.append
(x
)h
.append
(y
)font
=cv2
.FONT_HERSHEY_SIMPLEXimg
=cv2
.putText
(img
,str(i
),(h
[int(len(h
)/(2))],w
[int(len(w
)/2)]),font
,1,(255,255,255),2)
img
= Image
.fromarray
(np
.uint8
(img
))
img
.show
()
img
.save
(path
+'\\'+seg_img_name
+'_label.png')
https://github.com/LarkMi/SLIC
總結
以上是生活随笔為你收集整理的SLIC超像素分割并保存分割得到的超像素块,python代码的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。