2

假设我有一个 8 向的 freeman 链码如下,在一个 python 列表中:

freeman_code = [3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5]

方向将定义如下:

弗里曼代码说明

我需要将其转换为具有 1s 和 0s 值的可变维度的图像矩阵,其中 1s 将描述形状,例如:

image_matrix = [
[0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 1]
]

当然,以上并不是上述freeman代码的精确实现。python中是否有任何实现,或者任何实现这一目标的语言?我的想法(在python中):使用defaultdicts的defaultdict,默认为0:

ImgMatrixDict = defaultdict(lambda: defaultdict(lambda:0))

然后从一个中点开始,比如说ImgMatrixDict[25][25],然后根据我遍历的 freeman 代码值将值更改为 1。之后我将转换ImgMatrixDict为列表列表。

这是一个可行的想法还是有任何现有的库或建议来实现它?任何想法/伪代码将不胜感激。

PS:在性能方面,是的,这并不重要,因为我不会实时执行此操作,但通常代码长度约为 15-20 个字符。我假设一个 50*50 的矩阵就足够了。

4

2 回答 2

3

如果我正确理解您的问题:

import numpy as np 
import matplotlib.pyplot as plt

freeman_code = [3, 3, 3, 6, 6, 4, 6, 7, 7, 0, 0, 6]
img = np.zeros((10,10))

x, y = 4, 4 
img[y][x] = 1
for direction in freeman_code:
    if direction in [1,2,3]:
        y -= 1
    if direction in [5,6,7]:
        y += 1
    if direction in  [3,4,5]:
        x -= 1
    if direction in [0,1,7]:
        x += 1

    img[y][x] = 1

plt.imshow(img, cmap='binary', vmin=0, vmax=1)
plt.show()

在此处输入图像描述

于 2018-12-17T16:48:23.203 回答
1

这是python中的解决方案。字典不适应这个问题,你最好用list的list来模拟表。

D = 10

# DY, DX
FREEMAN = [(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)]

freeman_code = [3, 3, 3, 3, 6, 6, 6, 6, 0, 0, 0, 0]
image = [[0]*D for x in range(D)]


y = D/2
x = D/2
image[y][x] = 1

for i in freeman_code:
    dy, dx = FREEMAN[i]
    y += dy
    x += dx
    image[y][x] = 1

print("freeman_code")
print(freeman_code)
print("image")
for line in image:
    strline = "".join([str(x) for x in line])
    print(strline)


>0000000000
>0100000000
>0110000000
>0101000000
>0100100000
>0111110000
>0000000000
>0000000000
>0000000000
>0000000000

请注意,图像创建是以下内容的浓缩表达:

image = []
for y in range(D):
    line = []
    for x in range(D):
        line.append(0)
    image.append(line)

如果有一天,您需要更好的性能来处理更大的图像,有使用 numpy 库的解决方案,但需要对基本的 python 有很好的了解。这是一个例子:

import numpy as np

D = 10

# DY, DX
FREEMAN = [(0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1), (1, 0), (1, 1)]
DX = np.array([1, 1, 0, -1, -1, -1, 0, 1]) 
DY = np.array([0, -1, -1, -1, 0, 1, 1, 1]) 

freeman_code = np.array([3, 3, 3, 3, 6, 6, 6, 6, 0, 0, 0, 0])
image = np.zeros((D, D), int)

y0 = D/2
x0 = D/2
image[y0, x0] = 1

dx = DX[freeman_code]
dy = DY[freeman_code]

xs = np.cumsum(dx)+x0
ys = np.cumsum(dy)+y0

print(xs)
print(ys)

image[ys, xs] = 1

print("freeman_code")
print(freeman_code)
print("image")
print(image)

在这里,在以前的解决方案中使用“for”构建的所有循环都在 C 中快速处理。

于 2018-12-17T16:51:04.130 回答