当我使用下面的代码时,我得到了这个错误,如何处理它?
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.代码:
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() 发布于 2022-09-20 14:30:44
变量img1是从文件中加载的图像,如果它的RGB,则它的形状是(m,n, 3)。
因此,当您执行g[x, y] = f[x*sampling_rate, y*sampling_rate]时,我相信您正在将一个RGB像素放入数组g的一个uint8插槽中。
如果要使g保持灰度图像,则应将rgb图像转换为灰度图像,或将其直接加载到灰度模式中。
发布于 2022-09-20 16:31:31
您可以将正确的形状传递给新的图像,如下所示:
g = np.zeros(f.shape, dtype = 'uint8')但是请注意,您正在实现一个现有的函数。这做了所有的工作:
g = cv2.resize(f, None, fx=1/sampling_rate, fy=1/sampling_rate)https://stackoverflow.com/questions/73788262
复制相似问题