使用Python标记图像

问题描述 投票:5回答:1

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

我没有python编码的经验,我试图使用一个jupyter笔记本运行从答案提供的代码,但我不知道怎么能让它工作。我相信在导入图像时我做错了。我正在尝试从名为“images”的文件夹中导入所有图像,该文件夹位于“PATH”中。

这是完整的代码:

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笔记本版本:enter image description here

python opencv jupyter-notebook interactive
1个回答
2
投票

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

    for col in range(COLS):

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

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

© www.soinside.com 2019 - 2024. All rights reserved.