我对使用缓冲区协议在python,numpy和cython之间传递二进制数据感兴趣。查看PEP 3118,似乎在结构字符串语法中添加了一些内容,从而增加了对诸如命名字段和嵌套结构之类的有用功能的支持。
但是,似乎在这三个位置中,对缓冲区语法的所有范围的支持都受到限制。例如,假设我具有以下cython结构:
ctypedef packed struct ImageComp:
uint32_t width
uint32_t height
uint8_t *pixels
#Here is the appropriate struct format string representation
IMAGE_FORMAT = b'T{L:width:L:height:&B:pixels:}'
Run Code Online (Sandbox Code Playgroud)
尝试如下提取PEP-3118兼容字节字符串
cdef void *image_temp = malloc(sizeof(ImageComp))
IMAGE_SIZE = sizeof(ImageComp)
IMAGE_FORMAT = (<ImageComp[:1]>image_temp)._format
IMAGE_DTYPE = np.asarray(<ImageComp[:1]>image_temp).dtype
free(image_temp)
Run Code Online (Sandbox Code Playgroud)
失败,并显示以下错误消息:
Invalid base type for memoryview slice: ImageComp
因为键入的内存视图如果包含指针,则无法创建。
同样,view.array使用我的自定义字符串或使用python struct模块的calcsize函数创建时,会发出类似的警告struct.error: bad char in struct format。
我可以Py_buffer按照此处所述手动创建和填充对象,但是尝试将其转换为具有np.asarrayyields 的numpy数组ValueError: 'T{L:width:L:height:&B:pixels:}' is not a valid PEP …
我有兴趣提取给定 ttf 文件中所有字形的二次贝塞尔曲线信息。目前,使用 python 中的 ttfquery 库,我能够以a下列方式提取给定字形(例如)的轮廓:
from ttfquery import describe
from ttfquery import glyphquery
import ttfquery.glyph as glyph
char = "a"
font_url = "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf"
font = describe.openFont(font_url)
g = glyph.Glyph(char)
contours = g.calculateContours(font)
for contour in contours:
for point, flag in contour:
print point, flag
Run Code Online (Sandbox Code Playgroud)
这适用于字母字符,但它为数字、标点符号、空格等提供了以下关键错误:
Traceback (most recent call last):
File "demo.py", line 9, in <module>
contours = g.calculateContours(font)
File "/usr/local/lib/python2.7/dist-packages/ttfquery/glyph.py", line 33, in calculateContours
charglyf = glyf[self.glyphName]
File "/usr/local/lib/python2.7/dist-packages/FontTools/fontTools/ttLib/tables/_g_l_y_f.py", line 185, in __getitem__
glyph = …Run Code Online (Sandbox Code Playgroud)