matplotlib 为什么在Jupyter Notebook中尝试提取和粘贴图像时会出现ValueError?

b4wnujal  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(118)

我正在Jupyter Notebook上使用OPEN-CV,Matplotlib和NumPy进行计算机视觉项目(学校),我们必须从图像中提取正方形并将其粘贴到同一图像的其他部分(使用y/x轴的范围函数)。它工作得很好,但现在它一直显示我一个错误。
我的代码:

img = cv2.imread('Images/flower.jpg')
flower = img[2000:3200, 1300:2800]
img[0:1200, 0:1500] = img[1200:2400, 1500:3000] = img[2400:3600, 3000:4500] = flower

plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('more flowers')
plt.axis('on')
plt.show()

字符串
错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[12], line 3
      1 img = cv2.imread('Images/flower.jpg')
      2 flower = img[2000:3200, 1300:2800]
----> 3 img[0:1200, 0:1500] = img[1200:2400, 1500:3000] = img[2400:3600, 3000:4500] = flower
      5 plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
      6 plt.title('more flowers')

ValueError: could not broadcast input array from shape (1200,1500,3) into shape (1200,770,3)

dly7yett

dly7yett1#

我不确定这是否有效,因为我没有您正在使用的确切图像,但请尝试以下操作:

这段代码 * 应该 * 将花数组的大小调整为(1200,1500,3),以匹配img中目标切片的形状。

import cv2
import matplotlib.pyplot as plt

# Read the image
img = cv2.imread('Images/flower.jpg')

# Extract the flower region from the image
flower = img[2000:3200, 1300:2800]

# Resize the flower array to match the size of each destination slice
flower = cv2.resize(flower, (1500, 1200))

# Assign the resized flower array to the respective slices in img
img[0:1200, 0:1500] = flower
img[1200:2400, 1500:3000] = flower
img[2400:3600, 3000:4500] = flower

# Display the modified image
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title('More Flowers')
plt.axis('on')
plt.show()

字符串
当您尝试将花数组分配给img数组的不同切片时,形状必须匹配。

相关问题