[英]TypeError: Object of type uint8 is not JSON serializable
I'm having some problems with dumping a dictionary to a json file.我在将字典转储到 json 文件时遇到了一些问题。 The dictionary is made up of color tuples/values from an image, and is generated like so:
字典由图像中的颜色元组/值组成,生成如下:
import cv2, json
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):
if tuple(img[h, w]) in colors:
continue
else:
colors.add(tuple(img[h, w]))
col_dict[str(index)] = list(img[h, w])
index += 1
The following loop will extract all the different types of color values in an image and stores them in the dictionary, using the index
variable as the key.下面的循环将提取图像中所有不同类型的颜色值并将它们存储在字典中,使用
index
变量作为键。 The colors
set variable is used in another part of my program, so it can be ignored. colors
设置变量在我程序的另一部分使用,所以可以忽略。
The loop successfully creates a dictionary, but when executing the following code:循环成功创建了一个字典,但是在执行以下代码时:
with open("file.json", "w") as infile:
json.dump(col_dict, infile, indent=2)
The following error is produced:产生以下错误:
TypeError: Object of type uint8 is not JSON serializable
The code works when I define a dictionary and it's values manually, like so:当我手动定义字典和它的值时,代码可以工作,如下所示:
colors = {
"0" : (109, 87, 34),
"1" : (209, 87, 34),
"2" : (85, 98, 34), ...}
with open("file.json", "w") as infile:
json.dump(colors, infile)
I have no idea why it isn't working now, it still works for other programs that do the same thing.我不知道为什么它现在不起作用,它仍然适用于做同样事情的其他程序。 Thanks in advance.
提前致谢。
I've found the problem with the code.我发现了代码的问题。 CV2 image objects are
numpy.ndarrays
, and each pixel color value is a numpy.uint8
data type. CV2 图像对象是
numpy.ndarrays
,每个像素颜色值是一个numpy.uint8
数据类型。 Since json files do not understand numpy uint8 integers, it produced the error TypeError: Object of type uint8 is not JSON serializable
. Since json files do not understand numpy uint8 integers, it produced the error
TypeError: Object of type uint8 is not JSON serializable
.
Here is the solution to my code:这是我的代码的解决方案:
import cv2, json
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):
if tuple(img[h, w]) in colors:
continue
else:
value = (int(img[h, w][0]), int(img[h, w][1]), int(img[h, w][2])) # This converts each BGR value from uint8 to int.
colors.add(tuple(img[h, w]))
col_dict[str(index)] = value
index += 1
with open("file.json", "w") as infile:
json.dump(col_dict, infile, indent=2)
All I needed to do was convert the numpy uint8 object to a python integer.我需要做的就是将 numpy uint8 object 转换为 python Z157DB7ZDF5300235677515D326C89
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.