1

What is the problem in line 5? I copied directly from a book but getting this error:

py edge.py
Traceback (most recent call last):
  File "edge.py", line 5, in <module>
    rows,cols = img.shape
ValueError: too many values to unpack (expected 2)   

Code:

import cv2 


img = cv2.imread('489.jpg')
rows, cols = img.shape
sobel_horizontal = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
cv2.imshow('Input image', img)

cv2.waitKey()
user5858
  • 1,082
  • 4
  • 39
  • 79
  • 1
    why your title says syntax error? and [here is your answer](https://stackoverflow.com/a/19098258/6045800) – Tomerikoo Dec 07 '19 at 21:12

1 Answers1

3

As explained on OpenCV's website:

The shape of an image is accessed by img.shape. It returns a tuple of the number of rows, columns, and channels (if the image is color)

If an image is grayscale, the tuple returned contains only the number of rows and columns

Your code unpacks 2 values from the result of img.shape, so it works only for grayscale images.

If your image is in color, you should also unpack the third value. Otherwise you get the error that you ran into because you're trying to unpack 2 values when img.shape gives you 3 values.

The following will work for images with color:

rows, cols, channels = img.shape

However, as advised on OpenCV's website:

it is a good method to check whether the loaded image is grayscale or color.

That way, you'll know how many values to unpack and your program will work for both grayscale and color images.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56