matplotlib 将徽标添加到图像

jecbmhm3  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(162)

我使用Matplotlib创建了各种图形,其中一个是带有徽标和文本的图像。似乎每次我在第一个图像上绘制第二个图像时,它都会重新缩放整个图。
我试图使用范围参数,但整个图使用徽标大小来缩放,如下图所示。

from PIL import Image
import matplotlib.pyplot as plt

bkg = Image.open("C:/image/path")
logo = Image.open("C:/image/path")

fig, ax = plt.subplots(figsize=(16, 9))

ax.imshow(bkg.resize((1600, 900)))

logo_x = 700
logo_y = 400

logo_width = 100
logo_height = 50
logo_image = logo_image.resize((logo_width, logo_height))

logo_extent = (logo_x,logo_x + logo_width,logo_y + logo_height,logo_y)

ax.annotate(text="This is a Text", xy=(100, 450), color="white", size="xx-large")

ax.imshow(logo, extent=logo_extent)

plt.axis("off")

下面的图片是我试图实现的参考。标志有一个透明的背景。

4szc88ey

4szc88ey1#

徽标图像被拉伸,覆盖所有背景,因为 ax.imshow 指令的extent参数根据相对于整个图的坐标值进行缩放,而不仅仅是背景图像。
要将徽标添加到bkg的指定坐标处,您可以使用PIL中的 paste() 方法..

from PIL import Image  
import matplotlib.pyplot as plt  

bkg = Image.open("./back1.jpeg")  
logo = Image.open("./logo1.png") 

logo_x = 700  
logo_y = 400  
logo_width = 100  
logo_height = 50  

## Resize
bkg_resized = bkg.resize((1600, 900))  
logo_resized = logo.resize((logo_width, logo_height)).convert("RGBA")  

""" N.B. Converting to RGBA mode may be unnecessary, but it must be done when 
the image contains transparency info, such as an alpha channel, that should be preserved.
"""

# Paste the logo image onto the background image
bkg_resized.paste(logo_resized, (logo_x, logo_y), logo_resized)  

fig, ax = plt.subplots(figsize=(16, 9))  

# Display the background image with the logo image overlaid
ax.imshow(bkg_resized)  

ax.annotate(text="This is a Text", xy=(100, 450), color="white", size="xx-large")  

plt.axis("off")  
plt.show()

相关问题