python - 使用 Python 标记图像
问题描述
我最近偶然发现了这个问题: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 版本:
解决方案
您复制的代码在第二行末尾缺少一个冒号for
,应如下所示:
for col in range(COLS):
(不过,我会推荐一个好的 IDE,或者至少是一个语法检查器,来捕捉这些错误!)
修复任何语法问题后,您可以验证您在导入图像的方式上是否确实存在任何实际问题。但据我所知,您的代码很好 - 您正在打开一堆文件作为灰度图像并将它们传递给链接问题的代码。(但是,如果在语法错误消失后您仍然有问题,您可以编辑此问题或发布另一个问题。)
推荐阅读
- r - 如何根据R中两个不同长度的数据帧匹配IDS创建新列
- python - 如何删除python中纸浆中约束的语法错误
- c# - 在 1 个循环中将 2 行写入 TXT
- node.js - 我在 NodeJS mongoose 中的模型“Product”的路径“_id”处的值“shopping-cart”的 Cast to ObjectID failed
- java - 无法在更改位置时绘制多边形
- apache-spark - 无法从 MacOS 上的终端运行 spark-shell
- python - 如何排除一个列丢失和另一个具有特定值的条件?
- unity3d - 有没有办法将 FULL 3D REAL WORLD TERRAIN 加载到 Unity 中?
- javascript - 如何动态添加 jquery 滑块,包括幻灯片功能?
- javascript - 当调用 javasript 文件在 Wordpress 中不起作用时