0

I'm an absolute beginner in Python and I'm writing a program that uses my laptop's webcam.

I want to crop the output according to a crop factor and it seemed as easy as:

w = 1280
h = 720
crop_factor = 0.5

x_crop_start = int((w-w*crop_factor)/2)
x_crop_end = int(w-x_crop_start)
y_crop_start = int((h-h*crop_factor)/2)
y_crop_end = int(h-y_crop_start)

cropped_image = shifted_img[y_crop_start:y_crop_end, x_crop_start:x_crop_end]

Now the problem is my code doesn't work and I can't seem to understand the error shown on the console:

File "/Users/iacopo/Desktop/pyPong/faceStabilizer.py", line 74, in cv2.imshow("cropped", cropped_image) cv2.error: OpenCV(4.5.3) /private/var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/pip-req-build-8g_88acj/opencv/modules/highgui/src/window.cpp:1006: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

if I manually replace the variable names with integers everything works fine. Also if I leave y_crop_start and x_crop_start as variable names, but manually enter integers after the semicolon everything works just fine:

cropped_image = shifted_img[y_crop_start:500, x_crop_start:720]

I'm sure there's an easy fix and I feel very dumb for being stuck here.

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
Iacopo Boccalari
  • 1,195
  • 2
  • 12
  • 19
  • Iam not familiar with openCV shoud'nt `cropped_image = shifted_img[y_crop_start:y_crop_end, x_crop_start:x_crop_end]` should be `cropped_image = shifted_img[y_crop_start:y_crop_end][ x_crop_start:x_crop_end]` *(assuming we are dealing with 2D list)* – Anshul Aug 28 '21 at 11:30
  • Thanks for your reply. Unfortunately your solution gives me an unexpected result. I get no errors, so the code is alright, but the window size is not the expected one even if I manually enter values instead of variable names. So I'm no longer sure that is a 2D list... long story short: ```cropped_image = shifted_img[320:960][180:540] # this shows a weird sized window``` is different from ```cropped_image = shifted_img[180:540, 320:960] # this shows a window of the expected size``` – Iacopo Boccalari Aug 28 '21 at 12:54
  • As the error is tripped when you call `cv2.imshow("cropped", cropped_image)` I would check which `int` type you are using, I'm pretty sure most OpenCV objects dont support `np.uint32` but do support `int32` – DrBwts Aug 28 '21 at 13:38
  • the issue here isn't types of integer/number and Anshul's advice/code is just wrong (that's not how you slice a numpy array that has 2+ dimensions, or regular python lists). **the crop is empty**. that is what imshow is complaining about. figure out the size of `shifted_img` and compare to the slice bounds you use. – Christoph Rackwitz Aug 28 '21 at 14:22

0 Answers0