0

我正在学习 wxPython。我的问题是如何创建位图。我有每个像素的 R、G、B 值,但我不知道如何从中创建位图。我试过使用wx.BitmapFromBuffer,我不明白我应该如何创建这个缓冲区。我遍历了每个像素并以线性方式放入列表 R、G、B 组件,但它并没有画出我所期望的。你了解缓冲区应该如何构建吗?

我不想使用 wx.MemoryDC 在位图上绘制每个像素,因为它太慢了。

谢谢!

编辑:我使用 wxPython 演示中的方法 - RawBitmapAccess。

    buf = numpy.empty((w,h,3), numpy.uint8)
    n = 29000
    for i in xrange(w):
        for j in xrange(h):
            r = int(n*255*field[j,i])
            if r > 253: 
                r = 253
            buf[i, j, 0] = int(r)
            buf[i, j, 1] = int(r)
            buf[i, j, 2] = int(b)
            #dc.SetPen(wx.Pen(wx.Colour(r,r,b)))
            #dc.DrawPoint(i,j)
    bmp = wx.BitmapFromBuffer(w, h, buf)
    gc = wx.GraphicsContext.Create(dc)
    gc.DrawBitmap(bmp, 0, 0, w, h)

如果我取消注释我的旧绘图方式(循环中有两条注释线),那么我得到了我想要的 - 一个模糊的球。如果我不取消注释我有奇怪的图片 - 它被垂直分成几个片段,每个片段都有自己的模糊球,而且看起来有垂直线缺失像素。我以与演示程序相同的方式使用缓冲区。为什么我得到奇怪的图片?

编辑2:我想通了。我应该在循环中交换 i 和 j 。

4

1 回答 1

3

正如我在之前的答案中发布的那样,这是使用 numpy 完成的,并且在演示调用 RawBitmapAccess 中有一个示例。代码基本上看起来像,

def MakeBitmap2(self, red, green, blue, alpha=128):
    # Make an array of bytes that is DIM*DIM in size, with enough
    # slots for each pixel to have a RGB and A value
    #arr = makeByteArray( (DIM,DIM, 4) )
    arr = numpy.empty((DIM,DIM, 4), numpy.uint8)

    # just some indexes to keep track of which byte is which
    R, G, B, A = range(4)

    # initialize all pixel values to the values passed in
    arr[:,:,R] = red
    arr[:,:,G] = green
    arr[:,:,B] = blue
    arr[:,:,A] = alpha

    # Set the alpha for the border pixels to be fully opaque
    arr[0,     0:DIM, A] = wx.ALPHA_OPAQUE  # first row
    arr[DIM-1, 0:DIM, A] = wx.ALPHA_OPAQUE  # last row
    arr[0:DIM, 0,     A] = wx.ALPHA_OPAQUE  # first col
    arr[0:DIM, DIM-1, A] = wx.ALPHA_OPAQUE  # last col

    # finally, use the array to create a bitmap
    bmp = wx.BitmapFromBufferRGBA(DIM, DIM, arr)
    return bmp
于 2012-04-16T01:03:25.807 回答