You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用json.dump导出CV2颜色字典报uint8不可序列化问题

报错原因
  • OpenCV的imread接口读取到的图像像素值为numpy uint8类型,并非Python原生整数类型
  • 你代码中list(img[h, w])只是将numpy数组转为Python列表,列表内的元素仍为uint8类型,没有解决类型不兼容问题
  • 标准库json仅支持序列化Python原生数据类型,无法识别numpy自定义数值类型,因此触发TypeError: Object of type uint8 is not JSON serializable报错
  • 手动构造的字典中数值为Python原生int,符合json序列化要求,所以可以正常导出
解决方案

方案1:存储时直接转换数据类型(最推荐)

在写入字典时直接将像素值转为Python原生int,从根源避免类型不兼容问题,修改循环内的赋值逻辑即可:

import cv2, json
import numpy as np # 若之前未导入numpy可补充该行

img = cv2.imread("bg.png")
HEIGHT, WIDTH = img.shape[:2]

colors = set({})
col_dict = {}
index = 0

for h in range(HEIGHT):
    for w in range(WIDTH):
        pixel_tuple = tuple(img[h, w])
        if pixel_tuple in colors:
            continue
        colors.add(pixel_tuple)
        # 逐个将通道值转换为Python原生int
        col_dict[str(index)] = [int(channel) for channel in img[h, w]]
        index += 1

# 后续导出逻辑无需修改
with open("file.json", "w") as infile:
    json.dump(col_dict, infile, indent=2)

方案2:导出时增加序列化兼容规则

如果不想修改原字典生成逻辑,可以在json.dump时增加default参数,指定非原生类型的转换规则:

with open("file.json", "w") as infile:
    json.dump(
        col_dict, 
        infile, 
        indent=2,
        # 遇到uint8类型自动转成原生int
        default=lambda obj: int(obj) if isinstance(obj, np.uint8) else obj
    )

内容的提问来源于stack exchange,提问作者Jumanji176

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 15:54:07