我最近偶然发现了这个问题:Interactive labeling of images in jupyter notebook 我发现这很有趣。
我几乎没有python编码的经验,所以我尝试使用jupyter笔记本运行答案中提供的代码,但是我不知何故无法正常工作。我相信导入图像时做错了什么。我正在尝试从位于“ 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.
如果有人可以帮助我,我会很高兴。
编辑:
答案 0 :(得分:2)
您复制的代码在第二行for
的末尾缺少一个冒号,它看起来应该像这样:
for col in range(COLS):
(不过,我会推荐一个好的IDE,或者至少是一个语法检查器,以捕获这类错误!)
一旦修复了所有语法问题,就可以验证导入图像的方式是否确实存在任何实际问题。但是据我所知,您的代码很好-您正在打开一堆文件作为灰度图像,并将它们传递给链接问题中的代码。 (不过,如果语法错误消失后仍然存在问题,则可以编辑此问题或发布另一个问题。)