社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何使用Python PIL和Numpy检索相邻为黑色的白色像素的索引列表?

VaSaV • 4 年前 • 1683 次点击  

我花了好几个小时寻找一个类似的问题,但没有什么能让我满意。 我的问题是:我已经将一个PIL图像(代表一条运河)转换成了一个Numpy数组(使用PIL的“L”模式),我想检索其邻居是黑色的白色像素(实际上是它们的索引),而不使用 for循环 (图像真的很大)。 我想到了 NP哪里 但我不知道我应该如何使用它来解决我的问题,我也不知道它是否会比使用它更快 for循环 (因为我的目标是以最快的速度实现这一目标)。

我希望我足够清楚,我提前感谢您的回复!

编辑:例如,使用此图像( a simple canal ,它已经是黑白图像,所以 形象转换('L') 在这里不是很有用,但代码应该是通用的(如果可能的话),我会这样做:

import numpy as np
from PIL import Image

image = Image.open(canal)
image = image.convert("L")
array = np.asarray(image)
l = []
for i in range(1, len(array) - 1):
    for j in range(1, len(array[0]) - 1):
        if array[i][j] == 255 and (array[i+1][j] == 0 or array[i-1][j] == 0 or array[i][j+1] == 0 or array[i][j-1] == 0):
             l.append((i, j))

我希望获得 L 尽可能快:) 在下一张图片中,我将需要的像素涂成红色: here .

EDIT2:谢谢大家的帮助,成功了!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132487
文章 [ 3 ]  |  最新文章 4 年前
jyli
Reply   •   1 楼
jyli    4 年前

如果不考虑内存空间,我更喜欢像下面这样操纵遮罩。

# Step 1: Generate two masks of white and black.
mask_white = img == 255
mask_black = img == 0

# Step 2: Apply 8-neighborhood dilation on black mask
# if you want to use numpy only, you need to implement dilation by yourself.
# define function of 8-neighborhood dilation
def dilate_8nb(m):
    index_row, index_col = np.where(m)
    ext_index_row = np.repeat(index_row,9)
    ext_index_col = np.repeat(index_col,9)
    ext_index_row.reshape(-1,9)[:, :3]  += 1
    ext_index_row.reshape(-1,9)[:, -3:]  -= 1
    ext_index_col.reshape(-1,9)[:, ::3]  += 1
    ext_index_col.reshape(-1,9)[:, 2::3]  -= 1
    ext_index_row = np.clip(ext_index_row, 0, m.shape[0]-1)
    ext_index_col = np.clip(ext_index_col, 0, m.shape[1]-1)
    ret = m.copy()
    ret[ext_index_row, ext_index_col] = True
    return ret

ext_mask_black = dilate_8nb(mask_black)
# or just using dilation in scipy
# from scipy import ndimage
# ext_mask_black = ndimage.binary_dilation(mask_black, structure=ndimage.generate_binary_structure(2, 2))

# Step 3: take the intersection of mask_white and ext_mask_black
mask_target = mask_white & ext_mask_black

# Step 4: take the index using np.where
l = np.where(mask_target)

# modify this type to make it consistency with your result
l = list(zip(*l))
Carlos Horn
Reply   •   2 楼
Carlos Horn    4 年前

我想到的另一种可能性是使用最小过滤器。然而,我预计它会比第一个提议的解决方案慢,但在它的基础上构建更多的解决方案可能会有用。

import numpy as np
from scipy.ndimage import minimum_filter

# create a footprint that only takes the neighbours into account
neighbours = (np.arange(9) % 2 == 1).reshape(3,3)

# create a mask of relevant pixels, img should be your image as array
mask = np.logical_and(
    img == 255,
    minimum_filter(img, footprint=neighbours) == 0
)

# get indexes
indexes = np.where(mask)

# as list
list(zip(*indexes))
Carlos Horn
Reply   •   3 楼
Carlos Horn    4 年前

你可以用 numba 即时编译器来加速你的循环。

from numba import njit

@njit
def find_highlow_pixels(img):
    pixels = []
    for j in range(1, img.shape[0]-1):
        for i in range(1, img.shape[1]-1):
            if (
                img[j, i] == 255 and (
                    img[j-1, i]==0 or img[j+1,i]==0 or 
                    img[j, i-1]==0 or img[j, i+1]==0
                )
            ):
                pixels.append((j, i))
    return pixels