【问题标题】:How to add a value to all elements of a sliced 3D numpy array?如何为切片的 3D numpy 数组的所有元素添加值?
【发布时间】:2021-01-21 06:18:11
【问题描述】:

我的代码:

img = np.asarray(ibuffer).copy()
imgb = cv2.cvtColor(img, cv2.COLOR_BGR2Lab)
imgb[:,:,0] += bvalue
imgb = cv2.cvtColor(imgb,cv2.COLOR_LAB2BGR)
photo = Image.fromarray(imgb)
photo = resize(photo)
photo = ImageTk.PhotoImage(photo)
canvas.photo = photo
canvas.create_image(0,0,anchor="nw",image = photo)

我需要将“bvalue”变量的值添加到 imgb(3D numpy 数组)的第一维的所有元素中。当我尝试这个时,我收到以下错误消息:

Tkinter 回调异常 回溯(最近一次通话最后): call 中的文件“C:\Users\asaru\AppData\Local\Programs\Python\Python39\lib\tkinter_init_.py”,第 1884 行 返回 self.func(*args) 文件“e:\My Files\Project\Image Editor\Image Editor\test.py”,第 134 行,明亮

imgb[:,:,0] += bvalue

numpy.core._exceptions._UFuncOutputCastingError:无法使用转换规则“same_kind”将 ufunc 'add' 输出从 dtype('

【问题讨论】:

  • 请通过创建一些会导致相同错误的虚拟随机变量来使代码可重现。我们可能需要能够运行代码。看看提出问题的指南。 stackoverflow.com/help/how-to-ask

标签: python numpy image-processing tkinter


【解决方案1】:

您可以将整数添加到 numpy.uint8。如果您将 bvalue 转换为 int(并假设 bvalue 可以转换为 int),那么您的代码应该可以工作。

lab[:,:,0] += int(50.0)

上面的行用于使图像变亮。小心,因为通道是一个 uint8,如果超过 255,它会溢出。如果超过它,它会返回并继续 (255 + 11 = 10)。

【讨论】:

    【解决方案2】:

    检查Numpy Dtypes。您的变量 bvalue 是 Unicode String 类型,变量 imgb 是 unsigned int 类型。无法添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      • 2021-04-22
      相关资源
      最近更新 更多