Skip to main content
 首页 » 编程设计

python之scipy sobel 边缘检测,提取外部像素

2025年02月15日11davidwang456

尝试提取其自身区域内边缘内外的像素,目前我正在像这样应用 scipy Sobel 过滤器:

im = scipy.misc.imread(filename) 
im = im.astype('int32') 
dx = ndimage.sobel(im, axis=0) 
dy = ndimage.sobel(im, axis=1) 
 
mag = np.hypot(dx, dy)   
mag *= 255.0 / np.max(mag) 
 
scipy.misc.imsave('sobel.jpg', mag) 

目前的结果是:

想法是获取边缘检测之外的像素,例如这些区域:

如何提取 sobel 过滤器内外区域的数组?

请您参考如下方法:

这是一种使用交互式图像分割的方法。在这种方法中,您必须手动标记一些前景像素和一些背景像素,如下所示:

(我在 MS Paint 中做了标记。)下面的代码使用函数 skimage.segmentation.random_walker 进行图像分割,并生成这个分割图像:

(这种方法还可以处理具有更复杂背景区域的图像。)这是代码:

import skimage 
import skimage.viewer 
import skimage.segmentation 
import skimage.data 
import skimage.io 
import matplotlib.pyplot as plt 
import numpy as np 
 
img = skimage.io.imread("D:/Users/Pictures/img.jpg") 
imgLabeled = skimage.io.imread("D:/Users/Pictures/imgLabeled.jpg") 
 
redChannel = imgLabeled[:,:,0] 
greenChannel = imgLabeled[:,:,1] 
blueChannel = imgLabeled[:,:,2] 
markers = np.zeros(img.shape,dtype=np.uint) 
markers[(redChannel < 20) & (greenChannel > 210) & (blueChannel < 20)] = 1 
markers[(redChannel < 20) & (greenChannel < 20) & (blueChannel > 210)] = 2 
plt.imshow(markers) 
 
labels = skimage.segmentation.random_walker(img, markers, beta=1000, mode='cg') 
 
seg1 = np.copy(img) 
seg1[labels==2] = 0 
seg2 = np.copy(img) 
seg2[labels==1] = 0 
 
# plt.imsave("D:/Users/Pictures/imgSeg.png",seg1) 
 
plt.figure() 
plt.imshow(seg1) 
plt.figure() 
plt.imshow(seg2)