2017-01-27 7 views
1

私はバイナリ2D配列から、nピクセルの幅が正の領域に入る輪郭を得るために、(イメージの境界の百万のチェックなしで)最も簡単な方法でしたいと思います。Python:バイナリ2D配列の輪郭

例:例で呼び出すため

img = np.array([ 
       [0, 0, 0, 1, 1, 1, 1, 1, 0], 
       [0, 1, 1, 1, 1, 1, 1, 1, 1], 
       [0, 1, 1, 1, 0, 0, 0, 0, 0], 
       ]) 

1、j]、img [i、j-1]、img [i、j] = 1の場合には、 i、j + 1])は0である。

contour1 = get_countor(img, width = 1) 
contour1 = ([ 
       [0, 0, 0, 1, 0, 0, 0, 1, 0], 
       [0, 1, 1, 0, 1, 1, 1, 1, 1], 
       [0, 1, 0, 1, 0, 0, 0, 0, 0], 
      ]) 

幅= 1からのすべてのピクセルは、img [i、j] == 1を満たすものと同様に正であり、2つのインデックス離れて(真理距離)のピクセルが値0で存在する。

contour2 = get_countor(img, width = 2) 
contour2 = ([ 
       [0, 0, 0, 1, 1, 1, 1, 1, 0], 
       [0, 1, 1, 1, 1, 1, 1, 1, 1], 
       [0, 1, 1, 1, 0, 0, 0, 0, 0], 
      ]) 

ありがとうございます。

答えて

0
import numpy as np 
import pandas as pd 
import random 

df = pd.DataFrame([], columns=[0,1,2,3,4,5,6,7,8,9]) 

for i in np.arange(10): 
    df.loc[len(df)] = np.random.randint(0,2,10) 

df = df.astype(bool) 

contour = df & ((df-df.shift(-1, axis=0).fillna(1))|(df-df.shift(1,axis=0).fillna(1))|(df-df.shift(-1,axis=1).fillna(1))|(df-df.shift(1,axis=1).fillna(1))) 

出力:

DF:

enter image description here

輪郭:

enter image description here

希望この助けてください

0

あなたが探しているものは scipy.misc.imfilter(img, "find_edges")だと思います。

バイナリ配列imgを考えると、これは私がそれを見ると、あなたが255で分割する必要がありますので、幅= 2のフィルタが= 1の幅でフィルタを適用することによって得られる、0255で配列を生成します別の時間は、最後になるよう、あなたの関数が

def get_countor(img, width = 1): 
    for i in range(width): 
     img = scipy.misc.imfilter(img, "find_edges")/255 
    return img 
0

ない正確なこの質問に対する答えが、画像の輪郭を描画するための簡単な方法を共有するようになります。ただそれを探している人々のために。

from PIL import Image 
from PIL import ImageFilter 
import numpy as np 


def draw_contour(img, mask, contour_width, contour_color): 
    """Draw contour on a pillow image from a numpy 2D mask.""" 
    contour = Image.fromarray(mask) 
    contour = contour.resize(img.size) 
    contour = contour.filter(ImageFilter.FIND_EDGES) 
    contour = np.array(contour) 

    # make sure borders are not drawn 
    contour[[0, -1], :] = 0 
    contour[:, [0, -1]] = 0 

    # use a gaussian to define the contour width 
    radius = contour_width/10 
    contour = Image.fromarray(contour) 
    contour = contour.filter(ImageFilter.GaussianBlur(radius=radius)) 
    contour = np.array(contour) > 0 
    contour = np.dstack((contour, contour, contour)) 

    # color the contour 
    ret = np.array(img) * np.invert(contour) 
    if contour_color != 'black': 
     color = Image.new(img.mode, img.size, contour_color) 
     ret += np.array(color) * contour 

    return Image.fromarray(ret) 

このテスト出力を確認してください:enter image description here

私はこのPRのために働いている間、このソリューションを書きました。