使用Python的Matplotlib从中间开始制作覆盖图像的网格。
使用Python的Matplotlib从中间开始制作覆盖图像的网格。
大家好,我在制作一个从中间开始的篮球场图像的网格有些困惑 - 这意味着图像的宽度和高度都有一条中线,然后网格均匀地延伸到整个图片(左右和上下)。我正在使用这个作为示例:在matplotlib中绘制图像上的网格线。非常感谢任何帮助!我对matplotlib非常新手,希望向各位专家请教!\n谢谢\n这是我目前正在努力但并不起作用的代码(如果有帮助的话)\n
import matplotlib.pyplot as plt from PIL import Image import pylab as pl img = Image.open('PATH_TO_IMAGE') im = pl.imread('PATH_TO_IMAGE') width, height = img.size newh = height/2 neww = width/2 print(newh) print(neww) #dividing the new numbers by the court dimensions 60x110 both divided by two since height and width are divided by two. We want rectangles exactly 1 foot big in width and height dx, dy = int(newh/30), int(neww/55) print(dx) print(dy) grid_color = [0,0,0] im[:,::dy,:] = grid_color im[::dx,:,:] = grid_color plt.figure(figsize=(6,3.2)) # Show the result plt.imshow(im) plt.show()
\n这个代码对于一个图像完全有效,但对于其他图像则无效。这是错误信息:\nline 37, in \nim[:,::dy,:] = grid_color\nValueError: could not broadcast input array from shape (3) into shape (1322,119,4)\n由于版权问题,我无法粘贴篮球场的图像,但您可以使用谷歌上的任何2D篮球场图像,比如:https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.istockphoto.com%2Fillustrations%2Fbasketball-court-overhead&psig=AOvVaw3ORchlrt0TuWGaDMHoe5zn&ust=1629496920541000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCPCIk5yLvvICFQAAAAAdAAAAABAG
问题的原因是需要在Python的matplotlib库中在图像上创建一个以中心为起点的网格。解决方法是使用RGBA值来创建网格,并将其应用于图像的相应位置。
首先,我们需要了解RGBA值。RGBA代表红色、绿色、蓝色和透明度,它们是一种用于表示颜色的方式。每个值的范围是0到255,其中0表示没有颜色,255表示完全饱和的颜色。
在这个例子中,我们想要创建一个橙色的网格。橙色的RGBA值是(255, 165, 0, 255),其中255表示完全饱和的红色和绿色,0表示没有蓝色,255表示完全不透明。
为了在图像上创建一个以中心为起点的网格,我们可以使用以下代码:
grid_color = (255, 165, 0, 255) im[:, ::dy, :] = grid_color im[::dx, :, :] = grid_color
这段代码的作用是将网格颜色应用于图像的相应位置。第一行代码将网格颜色应用于图像的每一列,步长为dy。第二行代码将网格颜色应用于图像的每一行,步长为dx。
通过使用这些代码,我们可以很容易地在图像上创建一个以中心为起点的网格。这种方法可以用于各种类型的图像处理和可视化任务。