如何从python脚本构建JSON?

2024-05-10 07:14:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是JSON新手,我想从python脚本生成一个JSON文件

例如:

#take input from the user

num = int(input("Enter a number: "))

# prime numbers are greater than 1

if num > 1:

#check for factors

for i in range(2,num):
    if (num % i) == 0:
        print(num,"is not a prime number")
        print(i,"times",num//i,"is",num)
        break
else:
    print(num,"is a prime number")

# if the input number is less than or equal to 1, it is not prime

else: print(num,"is not a prime number")

对于上面的python脚本,如何生成JSON文件?有工具或软件吗?

我不想手动创建JSON文件。上面的代码只是一个例子。

我有一个目标检测和多输入图像的代码。在每个图像中,对象是相同的,但对象的位置是不同的。

输入图像:Trolley_Problem

电车模板:tram1

更新1:

import numpy as np
import cv2

# Read the main image

inputImage = cv2.imread("Trolley_Problem.jpg")

# Convert it to grayscale

inputImageGray = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Read the templates

tramTemplate = cv2.imread("tram1.jpg")

# Convert the templates to grayscale

tramTemplateGray = cv2.cvtColor(tramTemplate, cv2.COLOR_BGR2GRAY)

#Store width and height of the templates in w and h

h1,w1 = tramTemplateGray.shape

# Perform match operations.

tramResult = cv2.matchTemplate(inputImageGray,tramTemplateGray, cv2.TM_CCOEFF_NORMED)

# Specify a threshold

threshold = 0.75

# Store the coordinates of matched area in a numpy array

loc1 = np.where( tramResult >= threshold)

for pt in zip(*loc1[::-1]):
    cv2.rectangle(inputImage,pt, (pt[0] + w1, pt[1] + h1), (0,255,255), 1)
    cv2.putText(inputImage,"Tram Detected", (200,50), font, 0.5, 255)

# Show the final result

cv2.imwrite(r "Trolley_Problem_Result.jpg", inputImage)`

所以,我必须为这个对象检测程序生成JSON文件。

谢谢你


Tags: 文件theinptjsonnumberforinput
2条回答

python附带了一个json库,here's the docs

import json
#take input from the user

num = int(input("Enter a number: "))

# prime numbers are greater than 1

if num > 1:

#check for factors
prime_numbers = []
not_prime = []
for i in range(2,num):
    if (num % i) == 0:
        print(num,"is not a prime number")
        print(i,"times",num//i,"is",num)
        not_prime.append(num)
        break
    else:
        prime_numbers.append(num)
        print(num,"is a prime number")


fh = open("my_json.json", "a+")
fh.write(json.dumps({"prime": prime_numbers, "not_prime": not_prime})) # added an extra ')'.. code will now work
fh.close()

json很好:)

下面是一个将json模块与字典一起使用的示例

import json
# make sample dict with comprehension
dict1 = {k: v for (k, v) in enumerate(range(10))}
json1 = json.dumps(dict1)

具有以下价值

'{"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}'

所以,创建一个dict,使用模块。

相关问题 更多 >