sobel算子:
import numpy as np
import cv2
import os
def sobel(img, threshold):
G_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
G_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
rows = np.size(img, 0)
columns = np.size(img, 1)
mag = np.zeros(img.shape)
for i in range(0, rows - 2):
for j in range(0, columns - 2):
v = sum(sum(G_x * img[i:i + 3, j:j + 3]))
h = sum(sum(G_y * img[i:i + 3, j:j + 3]))
mag[i + 1, j + 1] = np.sqrt((v ** 2) + (h ** 2))
for p in range(0, rows):
for q in range(0, columns):
if mag[p, q] < threshold:
mag[p, q] = 0
return mag
path_color="G:\PointCloudUDA\inputt\PnpAda_release_data\mr_train\color_mask/"
files = os.listdir(path_color)
files.sort(key=lambda x: (x[:-4]))
for i in range(len(files)):
print(i)
cloud_dir = path_color + files[i]
img = cv2.imread(cloud_dir, 0) # read an image
mag = sobel(img, 10)
hh=np.where(mag==0.0,0.0,255.0)
# plt.imshow(hh,cmap="gray")
# plt.show()
cv2.imwrite("G:\PointCloudUDA\inputt\PnpAda_release_data\ct_train\line/"+files[i],hh)
细化:
import cv2
from skimage import morphology
import numpy as np
import glob
import os
from matplotlib import pyplot as plt
imageList = "G:\PointCloudUDA\inputt\PnpAda_release_data\ct_train\line/"
img_file = "G:\PointCloudUDA\inputt\PnpAda_release_data\ct_train\line_xi/"
files = os.listdir(imageList)
files.sort(key=lambda x: (x[:-4]))
# 批量处理图片
for i in range(len(files)):
print(i)
#np.empty((256*256, 4))
cloud_dir = imageList + files[i]
img = cv2.imread(cloud_dir, 0)
binary=np.array(img/255)
skeleton0 = morphology.skeletonize(binary)
#method2
# skel, distance = morphology.medial_axis(binary, return_distance=True) # 图片细化(骨架提取)
# skeleton0 = distance * skel
skeleton = skeleton0.astype(np.uint8)*255
cv2.imwrite(img_file+files[i], skeleton)
细化后结果: