0

我希望能够像这个示例一样绘制曲线,然后将其转换为近似曲线的函数。一些伪 python 代码可能看起来像

>> drawing = file.open('sample_curve.jpg')
>> approx_function = function_from_drawing(drawing, x_scale=10, y_scale=5, y_offset=3)
>> print approx_function(2.2) 
5.3

我认为您可以在每列中选择一个像素点,其中有一条线穿过它(如果有多条线,则决定使用最低的一个),然后用贝塞尔曲线将其平滑。我想我想知道的是什么已经存在这样的东西(当然它确实存在......)以及如何将它与python集成。另外,如果我找不到符合要求的东西,我将如何在 python 中实现它?使用矢量图会更容易吗?

4

1 回答 1

1

这是我初步的 hacky 解决方案:

from PIL import Image
import numpy as np

class Pic_Function():
    def __init__(self, picture_path):
        self.picture = Image.open(picture_path)
        self.pixels = self.picture.load()
        self.columns = []
        # is there really no image method to get a numpy array of pixels?
        for i in range(self.picture.size[0]):
            self.columns.append([self.pixels[i,j] for j in range(self.picture.size[1])])
        self.first_black = []
        for i in self.columns:
            try:
                self.first_black.append(self.picture.size[0] - i.index((0,0,0)))
            except ValueError:
                self.first_black.append(None)
        self.max, self.min = max(self.first_black), min([j for j in self.first_black if j != None])

    def at(self, x):
        upper_idx = int(math.ceil(x))
        lower_idx = upper_idx - 1
        try:
            upper = self.first_black[upper_idx]
            lower = self.first_black[lower_idx]
        except IndexError:
            return 0
        if None in [upper, lower]:
            return 0

        up_weight, low_weight = abs(upper-x), abs(lower-x)
        return (up_weight*upper + low_weight*lower)/(up_weight + low_weight)

    def norm_at(self, x, length):
        un_normed = self.at(x*self.picture.size[0]/length)
        return (un_normed - self.min)/self.max
于 2012-05-30T22:57:39.727 回答