如何在自定义Tensorflow层中修改图像? (提供的工作示例)

发布于 2025-02-10 22:05:23 字数 2687 浏览 2 评论 0原文

如何在Python 3上的Tensorflow 2中绘制填充的矩形作为自定义(数据增强)层?

输入预期输出
“输入”

AttributeError: Exception encountered when calling layer "remove_patch_5" (type RemovePatch).

'tensorflow.python.framework.ops.EagerTensor' object has no attribute '__array_interface__'

Call arguments received by layer "remove_patch_5" (type RemovePatch):
  • image=tf.Tensor(shape=(300, 300, 3), dtype=uint8)
  • training=True

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

from PIL import Image, ImageDraw


class RemovePatch(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def call(self, image, training=None):
        if not training:
            return image

        # This is the part that doesn't work
        # image_pil = Image.fromarray(image)
        """
        AttributeError: Exception encountered when calling layer "remove_patch_5" (type RemovePatch).

        'tensorflow.python.framework.ops.EagerTensor' object has no attribute '__array_interface__'

        Call arguments received by layer "remove_patch_5" (type RemovePatch):
          • image=tf.Tensor(shape=(200, 200, 3), dtype=uint8)
          • training=True
        """
        # image = np.array(
        #     ImageDraw.Draw(image_pil).rectangle(
        #         [50, 50, 100, 100], fill="#000000"
        #     )
        # )

        # This part works for adjusting brightness,
        # but no built-in function for drawing a
        # rectangle was found
        # image = tf.image.adjust_brightness(image, 0.5)

        return image


layer = RemovePatch()

image_file = "image.jpg"

try:
    open(image_file)
except FileNotFoundError:
    from requests import get

    r = get("https://picsum.photos/seed/picsum/300/300")
    with open(image_file, "wb") as f:
        f.write(r.content)

with Image.open(image_file) as img:
    img = np.array(img)
    augmented = layer(img, training=True)

    augmented = np.array(augmented)

    # plt.imshow(img)
    plt.imshow(augmented)

show_expected = False
if show_expected:
    with Image.open(image_file) as img:
        ImageDraw.Draw(img).rectangle([50, 50, 100, 100], fill="#000000")

        plt.imshow(img)

How can I draw a filled rectangle as a custom (data augmentation) layer in Tensorflow 2 on Python 3?

InputExpected output
inputexpected output

With image_pil = Image.fromarray(image), I get the error:

AttributeError: Exception encountered when calling layer "remove_patch_5" (type RemovePatch).

'tensorflow.python.framework.ops.EagerTensor' object has no attribute '__array_interface__'

Call arguments received by layer "remove_patch_5" (type RemovePatch):
  • image=tf.Tensor(shape=(300, 300, 3), dtype=uint8)
  • training=True

Example

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

from PIL import Image, ImageDraw


class RemovePatch(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def call(self, image, training=None):
        if not training:
            return image

        # This is the part that doesn't work
        # image_pil = Image.fromarray(image)
        """
        AttributeError: Exception encountered when calling layer "remove_patch_5" (type RemovePatch).

        'tensorflow.python.framework.ops.EagerTensor' object has no attribute '__array_interface__'

        Call arguments received by layer "remove_patch_5" (type RemovePatch):
          • image=tf.Tensor(shape=(200, 200, 3), dtype=uint8)
          • training=True
        """
        # image = np.array(
        #     ImageDraw.Draw(image_pil).rectangle(
        #         [50, 50, 100, 100], fill="#000000"
        #     )
        # )

        # This part works for adjusting brightness,
        # but no built-in function for drawing a
        # rectangle was found
        # image = tf.image.adjust_brightness(image, 0.5)

        return image


layer = RemovePatch()

image_file = "image.jpg"

try:
    open(image_file)
except FileNotFoundError:
    from requests import get

    r = get("https://picsum.photos/seed/picsum/300/300")
    with open(image_file, "wb") as f:
        f.write(r.content)

with Image.open(image_file) as img:
    img = np.array(img)
    augmented = layer(img, training=True)

    augmented = np.array(augmented)

    # plt.imshow(img)
    plt.imshow(augmented)

show_expected = False
if show_expected:
    with Image.open(image_file) as img:
        ImageDraw.Draw(img).rectangle([50, 50, 100, 100], fill="#000000")

        plt.imshow(img)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅黛梨妆こ 2025-02-17 22:05:24

@bui #comment12852939_72766606“>注释:

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

from PIL import Image, ImageDraw


class RemovePatch(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def call(self, image, training=None):
        if not training:
            return image

        image_pil = Image.fromarray(image.numpy())
        ImageDraw.Draw(image_pil).rectangle([50, 50, 100, 100], fill="#000000")
        image = np.array(image_pil)

        return image


layer = RemovePatch()

image_file = "image.jpg"

try:
    open(image_file)
except FileNotFoundError:
    from requests import get

    r = get("https://picsum.photos/seed/picsum/300/300")
    with open(image_file, "wb") as f:
        f.write(r.content)

with Image.open(image_file) as img:
    img = np.array(img)

    augmented = layer(img, training=True)
    augmented = Image.fromarray(augmented)

    plt.imshow(augmented)

A working solution with @bui's comment:

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

from PIL import Image, ImageDraw


class RemovePatch(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def call(self, image, training=None):
        if not training:
            return image

        image_pil = Image.fromarray(image.numpy())
        ImageDraw.Draw(image_pil).rectangle([50, 50, 100, 100], fill="#000000")
        image = np.array(image_pil)

        return image


layer = RemovePatch()

image_file = "image.jpg"

try:
    open(image_file)
except FileNotFoundError:
    from requests import get

    r = get("https://picsum.photos/seed/picsum/300/300")
    with open(image_file, "wb") as f:
        f.write(r.content)

with Image.open(image_file) as img:
    img = np.array(img)

    augmented = layer(img, training=True)
    augmented = Image.fromarray(augmented)

    plt.imshow(augmented)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文