gpt4 book ai didi

python - 将三重指针数组转换为 numpy 数组或列表 python

转载 作者:太空宇宙 更新时间:2023-11-04 04:27:54 26 4
gpt4 key购买 nike

我通过将 C 代码集成到我的 Python 程序中来加速我的程序。我正在使用 ctypes 从 python 中执行 c 中的函数。

c 程序:

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define MAX_ITERATIONS 1000

static void calculate_pixel(int x, int y, int size, float*** img){
int i = 0;
float a = 0.0, b = 0.0;

while(a*a+b*b <= 4.0 && i < MAX_ITERATIONS){
float temp_a = a;
a = a*a - b*b + x;
b = 2*a*b + y;

i++;
}

float temp[3];
memset(&temp, 0, sizeof(float)*3);

if(i != MAX_ITERATIONS){
float brightness = logf(1.75 + i - logf(log(a*a + b*b))) / log(MAX_ITERATIONS);
temp[0] = brightness;
temp[1] = brightness;
temp[2] = 1;
}

memcpy(img[x][y], &temp, sizeof(float)*3);
}

float*** mandel(int size){
ssize_t len = (size)*sizeof(float*);
float*** img = malloc(len);

int x, y;
for(x = 0; x < size; x++){
img[x] = malloc(len);
for(y = 0; y < size; y++){
img[x][y] = malloc(sizeof(float)*3);
calculate_pixel(x, y, size, img);
}
}

return img;
}

Python 程序:

 from ctypes import *
import matplotlib.pyplot as pl

size = 1000
lib = './mandelbrot3.so'

dll = cdll.LoadLibrary(lib)
dll.mandel.argtypes = [c_int]

#what i get in return from the c program
dll.mandel.restype = POINTER(POINTER(POINTER(c_float*3)*size)*size)

#calling function "mandel" in c program
res = dll.mandel(size)

#printing first value, does work this way
print(res.contains[0].contains[0].contains[0])

#creating a picture with pyplot, and inserting the array this way,
#does not work because its pointers
pl.imshow(res.contains)
pl.show()

dll.mandel.restype是一个三重指针,大小为:1000*1000*3。这是创建一个大小为 1000*1000 像素的图片,3 个 float 是 rgb 值。

所以我的问题是我从 c 程序返回的只是一个三重指针。我需要能够将其转换为普通的 3d python 列表或 numpy 数组。有没有比使用 for 循环读取指针数组中的所有元素并将它们插入到新列表或 numpy 数组更好的方法?

最佳答案

我不确定这个三重指针业务,但是从 C 到 numpy 的数组是这样工作的:

假设您已经收到一个 ctypes POINTER 到您的图像缓冲区,并且您知道 heightwidth 和数据类型...

您可以像这样从缓冲区中创建一个与图像大小相同的 ctypes 数组:

arr = (c_float * height * width * 3).from_address(addressof(data.contents))

在这种情况下,dataPOINTER

然后使用buffer kwarg从它创建一个ndarray:

import numpy as np
img = np.ndarray(buffer=arr, dtype=np.float32, shape=(height, width, 3))

关于python - 将三重指针数组转换为 numpy 数组或列表 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39712181/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com