Reputation: 46
I have this code, but I can't figure out why it gives an error: ValueError: operands could not be broadcast together with shapes (842,474) (844,476)
Code:
import numpy as np
from skimage.io import imread, imshow
from scipy.signal import convolve2d
family = imread('image.jpg')
gray_image = np.mean(family, axis=2)
kernel1 = np.array([[1, 2, 1],
[0, 0, 0],
[-1, -2, -1]])
conv_im1 = convolve2d(gray_image, kernel1, 'same')
kernel2 = np.array([[1, 0, -1],
[2, 0, -2],
[1, 0, -1]])
conv_im2 = convolve2d(gray_image, kernel2)
edge_image = np.sqrt(conv_im1**2 + conv_im2**2)
ValueError: operands could not be broadcast together with shapes (842,474) (844,476)
Any ideas?
I do not understand arrays and matrices at all, so please help me please.
Upvotes: 2
Views: 1688
Reputation: 538
The error message indicates that the arrays being used in the operation (conv_im1**2 + conv_im2**2)
have different shapes. "Shapes" in this context referrs to the dimensionality and size attributes of the matrices, you can read more about it here. Specifically, conv_im1
has a shape of (842, 474) and conv_im2
has a shape of (844, 476).
To fix this, you can either use the 'same' option in the convolve2d
function for conv_im2
as well, which will make its shape the same as conv_im1
:
conv_im2 = convolve2d(gray_image, kernel2, 'same')
Or you can manually crop the edges of conv_im2
to match the shape of conv_im1
:
conv_im2_cropped = conv_im2[1:-1, 1:-1]
edge_image = np.sqrt(conv_im1**2 + conv_im2_cropped**2)
Both options may result in loss of some edge pixels, so the choice will depend on your specific use case.
Upvotes: 1
Reputation: 399
You are not convolving the image by the "same" way.
conv_im1 = convolve2d(gray_image, kernel1, 'same')
conv_im2 = convolve2d(gray_image, kernel2)
As you can see in the first call you passed the "same", while not in the second call, this makes scipy to use its default value which is "full": "full" will have the output with different shape than the output, not like "same" which will have the output with identical shape to the input.
So in summary, the calls to convolve2d resulted two arrays with different shapes, to fix it you need to put the same mode parameter in both of them ["full", "same", "valid"]
Upvotes: 2