在 PIL 和 CV2 之间保存图像
Save Image between PIL and CV2
我现在想创建一个图像,
并在上面放一些文字。
但现在我有一个问题
这是我使用的代码
from PIL import Image , ImageDraw , ImageFont
import cv2
import numpy as np
#Create a Image
p_image = Image.new('L' , (960 , 720) , 50)
# Put text on it
text = 'Hello World\nHello World\nHello World\nHello World\nHello World\nHello World'
draw = ImageDraw.Draw(p_image)
draw.multiline_text(
(0 , 0) ,
text ,
font = ImageFont.truetype('font.ttf' , size = 16) ,
fill = 255)
# Save it by PIL
p_image.save('1.png')
#Convert to CV2 then save it
c_image = np.array(p_image)
cv2.imwrite('2.png' , c_image)
两种方法都得到相同的图像
但是PIL和cv2的大小差别很大
PIL 一个是 2.27KB
CV2 一个是 5.30KB
有人能告诉我为什么吗?
The picture
它们是两个不同的模块,可能使用不同版本的不同库,这些库对要使用的最佳过滤器和压缩做出不同的决定。
为了查看图像是如何保存的,请尝试使用以下任一命令检查两张图像:
pngcheck -v image.png
exiftool image.png
magick identify -verbose image.png
我发现这样比较最简单:
magick identify -verbose a.png > a
magick identify -verbose b.png > b
opendiff a b
我现在想创建一个图像, 并在上面放一些文字。
但现在我有一个问题
这是我使用的代码
from PIL import Image , ImageDraw , ImageFont
import cv2
import numpy as np
#Create a Image
p_image = Image.new('L' , (960 , 720) , 50)
# Put text on it
text = 'Hello World\nHello World\nHello World\nHello World\nHello World\nHello World'
draw = ImageDraw.Draw(p_image)
draw.multiline_text(
(0 , 0) ,
text ,
font = ImageFont.truetype('font.ttf' , size = 16) ,
fill = 255)
# Save it by PIL
p_image.save('1.png')
#Convert to CV2 then save it
c_image = np.array(p_image)
cv2.imwrite('2.png' , c_image)
两种方法都得到相同的图像
但是PIL和cv2的大小差别很大
PIL 一个是 2.27KB
CV2 一个是 5.30KB
有人能告诉我为什么吗?
The picture
它们是两个不同的模块,可能使用不同版本的不同库,这些库对要使用的最佳过滤器和压缩做出不同的决定。
为了查看图像是如何保存的,请尝试使用以下任一命令检查两张图像:
pngcheck -v image.png
exiftool image.png
magick identify -verbose image.png
我发现这样比较最简单:
magick identify -verbose a.png > a
magick identify -verbose b.png > b
opendiff a b