要在图像上绘制正方形,可以使用matplotlib中的Rectangle。在import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
imageArray = plt.imread('earth.jpg')
print('type of imageArray is ', type(imageArray))
print('shape of imageArray is ', imageArray.shape)
fig, ax = plt.subplots(1)
plt.imshow(imageArray)
square = patches.Rectangle((100,100), 20,20, color='RED')
ax.add_patch(square)
plt.show()
如果您真的想更改每个单独的像素,可以迭代行/列并将每个像素设置为[255,0,0]。下面是一个示例(如果您朝这个方向发展,您将希望包含索引器错误的异常处理):
^{pr2}$
编辑:
改变像素值的更有效的解决方案是使用数组切片。在def drawRedSquare(image, location, size):
x,y = location
w,h = size
image[y:y+h,x:x+w] = np.ones((w,h,3)) * [255,0,0]
return image