1

So I wrote code to crop out the ball in the attached picture and paste it somewhere else. But despite providing the correct dimensions, I keep getting an error.

import cv2

img=cv2.imread('messi.jpg',1)

ball=img[448:511,426:486]
img[190:253,450:510]=ball
cv2.imshow('messi',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Error i get while executing this:

line 6, in img[190:253,450:510]=ball ValueError: could not broadcast input array from shape (49,60,3) into shape (63,60,3)

I would be really grateful if someone could help me out with this. Thanks!
The picture for reference:

image

nathancy
  • 42,661
  • 14
  • 115
  • 137
DeadAsDuck
  • 11
  • 2

2 Answers2

1

The height of the input image is only 497 pixels but you are trying to access rows upto 511 in the following line:

ball=img[448:511, 426:486]
             ^

As a result, numpy is selecting rows only upto the maximum number of rows i.e. 497. Therefore, you are getting an ROI of size (49,60,3) because 497 - 448 = 49.

Make sure you handle the border cases correctly. Just for a reminder, when accessing OpenCV images using numpy indexing, rows are the first dimension and columns are the second dimension i.e. the access pattern is as follows:

ball = img[rowStart : rowEnd, columnStart : columnEnd]
sgarizvi
  • 16,623
  • 9
  • 64
  • 98
-1

Are you sure you are cropping the image right with the same library? Use of two different libraries is not recommended. Eg: PIL and CV2 both crop the image but from different start coordinates.

  • You can see in his code that he is using only opencv. Also, he is cropping and pasting based on the numpy arrays retrieved from an image.. He is using opencv library only to load the image(s). Did you look at his code? – WiseDev Jul 01 '19 at 07:06