【问题标题】:Labeling images using Python使用 Python 标记图像
【发布时间】:2019-08-06 00:05:06
【问题描述】:

我最近偶然发现了这个问题:Interactive labeling of images in jupyter notebook,我觉得这很有趣。

在 Python 编码方面几乎没有经验,我尝试使用 Jupyter Notebook 从答案中运行提供的代码,但不知何故无法让它工作。我相信我在导入图像时做错了什么。我正在尝试从位于“PATH”中的名为“images”的文件夹中导入所有图像。

完整代码如下:

import cv2
import os

import ipywidgets as widgets
import functools

images_list = []

os.chdir(PATH)
# Load in the images
for filepath in os.listdir('images/'):
    images_list.append(cv2.imread('images/{0}'.format(filepath),0))


COLS = 4
ROWS = 2
IMAGES = images_list 
IMG_WIDTH = 200
IMG_HEIGHT = 200

def on_click(index):
    print('Image %d clicked' % index)


rows = []

for row in range(ROWS):
    cols = []
    for col in range(COLS):
        index = row * COLS + col
        image = widgets.Image(
            value=IMAGES[index], width=IMG_WIDTH, height=IMG_HEIGHT
        )
        button = widgets.Button(description='Image %d' % index)
        # Bind the click event to the on_click function, with our index as argument
        button.on_click(functools.partial(on_click, index))

        # Create a vertical layout box, image above the button
        box = widgets.VBox([image, button])
        cols.append(box)

    # Create a horizontal layout box, grouping all the columns together
    rows.append(widgets.HBox(cols))

# Create a vertical layout box, grouping all the rows together
result = widgets.VBox(rows)

编辑

修复语法错误后,出现以下错误:

--------------------------------------------------------------------------- 
TraitError 
Traceback (most recent call last) <ipython-input-87-2ca2a1eb59b4> in <module>()
     36         index = row * COLS + col
     37         image = widgets.Image(
---> 38             value=IMAGES[index], width=IMG_WIDTH, height=IMG_HEIGHT
     39         )
     40         button = widgets.Button(description='Image %d' % index)

~\Anaconda3\lib\site-packages\ipywidgets\widgets\widget.py in __init__(self, **kwargs)
    409         """Public constructor"""
    410         self._model_id = kwargs.pop('model_id', None)
--> 411         super(Widget, self).__init__(**kwargs)
    412
    413         Widget._call_widget_constructed(self)

~\Anaconda3\lib\site-packages\traitlets\traitlets.py in __init__(self, *args, **kwargs)
    995             for key, value in kwargs.items():
    996                 if self.has_trait(key):
--> 997                     setattr(self, key, value)
    998                 else:
    999                     # passthrough args that don't set traits to super

~\Anaconda3\lib\site-packages\traitlets\traitlets.py in __set__(self, obj, value)
    583             raise TraitError('The "%s" trait is read-only.' % self.name)
    584         else:
--> 585             self.set(obj, value)
    586 
    587     def _validate(self, obj, value):

~\Anaconda3\lib\site-packages\traitlets\traitlets.py in set(self, obj, value)
    557 
    558     def set(self, obj, value):
--> 559         new_value = self._validate(obj, value)
    560         try:
    561             old_value = obj._trait_values[self.name]

~\Anaconda3\lib\site-packages\traitlets\traitlets.py in _validate(self, obj, value)
    589             return value
    590         if hasattr(self, 'validate'):
--> 591             value = self.validate(obj, value)
    592         if obj._cross_validation_lock is False:
    593             value = self._cross_validate(obj, value)

~\Anaconda3\lib\site-packages\traitlets\traitlets.py in validate(self, obj, value)
   2024         if isinstance(value, bytes):
   2025             return value
-> 2026         self.error(obj, value)
   2027 
   2028 

~\Anaconda3\lib\site-packages\traitlets\traitlets.py in error(self, obj, value)
    623             e = "The '%s' trait must be %s, but a value of %r was specified." \
    624                 % (self.name, self.info(), repr_type(value))
--> 625         raise TraitError(e)
    626 
    627     def get_metadata(self, key, default=None):

TraitError: The 'value' trait of an Image instance must be a bytes object, but a value of 
    array([[232, 242, 243, ..., 243, 246, 232],
           [244, 254, 255, ..., 254, 255, 243],
           [244, 254, 255, ..., 254, 255, 242],
           ...,
           [242, 253, 253, ..., 254, 254, 243],
           [245, 255, 255, ..., 255, 255, 244],
           [238, 249, 248, ..., 245, 245, 234]], dtype=uint8) 
    <class 'numpy.ndarray'> 
was specified.

编辑

这是我的 Jupyter Notebook 版本:

【问题讨论】:

  • 对于您编辑的问题: TraitError 看起来 Traitlets 包需要一个 Bytes 对象,但 IPyWidget 正在向它发送一个 numpy 数组。考虑到您自己没有对 numpy 做任何事情,我猜这是一个兼容性问题。您使用的是什么版本的 ipywidgets?特质呢?它们兼容吗?
  • @NiayeshIsky 感谢您的评论。我已经用我的 jupyter 版本更新了我的问题,但我不知道如何检查 traitlets。你会怎么做?谢谢。
  • 看起来你正在使用 Anaconda,所以根据this answer,只需运行conda env export -n YOUR_ENV_NAME &gt; environment.yml 并在输出environment.yml 文件中查找traitlets。 (或者您可以pastebin 整个输出文件并在此处链接到它,如果您愿意的话。)

标签: python opencv jupyter-notebook interactive


【解决方案1】:

您复制的代码在第二个for 行末尾缺少一个冒号,应如下所示:

    for col in range(COLS):

(不过,我会推荐一个好的 IDE,或者至少是一个语法检查器,来捕捉这些错误!)

解决任何语法问题后,您可以验证您在导入图像的方式上是否确实存在任何实际问题。但据我所知,您的代码很好 - 您正在打开一堆文件作为灰度图像并将它们传递给链接问题的代码。 (如果语法错误消失后仍有问题,您可以编辑此问题或发布另一个问题。)

【讨论】:

  • 感谢您指出我的错字!我修复了它,但现在我收到另一条错误消息(请参阅更新的问题)
  • @henry,如果您编辑您的原件并获得答案,只需在您自己的问题下方添加您面临的新问题,在“编辑:”之后,以便每个人都可以追溯发生的事情。干杯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 2017-11-12
  • 1970-01-01
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多