I am getting this error when I use the following code, how can I deal with it
TypeError Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
ValueError Traceback (most recent call last)
<ipython-input-20-e475e9fcaba7> in <module>
17 ShowImage(img2)
18
---> 19 main()
1 frame
<ipython-input-20-e475e9fcaba7> in image_downsampling(f, sampling_rate)
8 for x in range(nr_s):
9 for y in range(nc_s):
---> 10 g[x, y] = f[x*sampling_rate, y*sampling_rate]
11 return g
12
ValueError: setting an array element with a sequence.
Code:
import numpy as np
import cv2
def image_downsampling(f, sampling_rate):
nr, nc = f.shape[:2]
nr_s, nc_s = nr // sampling_rate, nc // sampling_rate
g = np.zeros([nr_s, nc_s], dtype = 'uint8')
for x in range(nr_s):
for y in range(nc_s):
g[x, y] = f[x*sampling_rate, y*sampling_rate]
return g
def main():
img1 = cv2.imread("Barbara.JPG", -1)
img2 = image_downsampling(img1, 2)
ShowImage(img1)
ShowImage(img2)
main()
CodePudding user response:
The variable img1
is an image loaded from a file, I believe its shape is (m,n, 3)
if its RGB.
So when you do g[x, y] = f[x*sampling_rate, y*sampling_rate]
I believe you are putting a RGB pixel into a uint8
slot of the array g
.
If you want to keep g
a grayscale image, you should transform your rgb image into a grayscale one, or load it directly in grayscale mode
CodePudding user response:
You can transfer the correct shape to the new image like this:
g = np.zeros(f.shape, dtype = 'uint8')
But please note that you are implementing an existing function. This is doing the whole job:
g = cv2.resize(f, None, fx=1/sampling_rate, fy=1/sampling_rate)