Python cairo将图形另存为np数组会给出奇怪的结果
尝试运行我的示例:Python cairo将图形另存为np数组会给出奇怪的结果,python,numpy,matplotlib,cairo,Python,Numpy,Matplotlib,Cairo,尝试运行我的示例: import numpy as np import cairo import matplotlib.pyplot as plt img_size = 28 size = 0.8 color = (255, 0, 0) thickness = 2 data = np.zeros((img_size, img_size, 3), dtype=np.uint8) surface = cairo.ImageSurface.create_for_data( data, cair
import numpy as np
import cairo
import matplotlib.pyplot as plt
img_size = 28
size = 0.8
color = (255, 0, 0)
thickness = 2
data = np.zeros((img_size, img_size, 3), dtype=np.uint8)
surface = cairo.ImageSurface.create_for_data(
data, cairo.FORMAT_RGB16_565, img_size, img_size
)
cr = cairo.Context(surface)
# fill with solid white
cr.set_source_rgb(1, 1, 1)
cr.paint()
size = img_size * size - thickness
cr.rectangle((img_size - size) / 2, (img_size - size) / 2, size, size)
cr.set_line_width(thickness)
cr.set_source_rgb(*color)
cr.stroke()
surface.write_to_png("shape.png")
plt.imshow(data)
plt.savefig("shape_from_np.png")
shape.png看起来像:
_np.png中的形状看起来像:
我在想也许我错过了格式,或者通道/形状,但是如果我像
data[:,:,0]
那样打印红色层,它在下半部分也会显示奇怪的0值,我不知道为什么。在我找到的文档ImageSurface.create_from_png(…)
所以我使用了您的'shape.png'
来测试它将对png图像使用什么值
import cairo
surface = cairo.ImageSurface.create_from_png('shape.png')
print('format:', surface.get_format())
print('width :', surface.get_width())
print('height:', surface.get_height())
print('stride:', surface.get_stride())
print('stride/width:', surface.get_stride()/surface.get_width())
这就给了
format: 1
width : 28
height: 28
stride: 112
stride/width: 4.0
我发现format:1
意味着cairo.format.RGB24
,在文档中我发现它需要32位
像素,这意味着4个字节
data = np.zeros((img_size, img_size, 4), dtype=np.uint8)
同样的4
给了我stride/width
(stride/28
)
使用这些值,我可以创建正确的图像,但是BGR
而不是RGB
所以它仍然需要一些改变
但是cv2
使用BGR
图像,并且它可以正确地保存图像而不进行任何更改
import cv2
cv2.imwrite('cv2.png', data)
Doc:,我知道,对于RGB16_565,最后一个轴的大小为2。RGB24的大小为4。我希望最后一个轴的大小为3,分别为红色、绿色和蓝色。在这种情况下,它们不是这个意思吗?我仔细看了一下,最后一个轴上的最后一个(第四个)元素似乎只是一个占位符。因此,如果我们删除它,并翻转值,它将起作用:np.flip(data[:,:,:3],-1)
。即使在文档中,您也可以阅读“像素是一个32位的量,上面的8位未使用。”
我认为它可以使用一种方法来处理RGB24
和ARGB32
,它们将这个位置用于alpha通道。
import numpy as np
import cairo
import matplotlib.pyplot as plt
img_size = 28
size = 0.8
color = (255, 0, 0)
thickness = 2
data = np.zeros((img_size, img_size, 4), dtype=np.uint8)
surface = cairo.ImageSurface.create_for_data(data, cairo.FORMAT_RGB24, img_size, img_size)
cr = cairo.Context(surface)
# fill with solid white
cr.set_source_rgb(1, 1, 1)
cr.paint()
size = int(img_size * size) - thickness
cr.rectangle((img_size - size) / 2, (img_size - size) / 2, size, size)
cr.set_line_width(thickness)
cr.set_source_rgb(*color)
cr.stroke()
plt.imshow(data)
plt.savefig("shape_from_np.png")
surface.write_to_png("shape.png")
import cv2
cv2.imwrite('cv2.png', data)