cv2.polylines()画出来全是点?不连续?如何读取.json文件的点并画为线保存?

那是因为cv2.polylines()没有完全按照官网格式写。就会出现画出来的不是线,而是点。

例如

 cv2.polylines()画出来全是点?不连续?如何读取.json文件的点并画为线保存?_第1张图片

 而需要的结果是将点连成线:

cv2.polylines()画出来全是点?不连续?如何读取.json文件的点并画为线保存?_第2张图片

特别注意不是:

cv2.polylines(image, points, isClosed, color, thickness) 

而是:

cv2.polylines(image, [points], isClosed, color, thickness) 

更正后的点的输入就可以正常画出线了。

官网用法:

Python OpenCV - cv2.polylines() method - GeeksforGeeks

然后添加一个例子,该例子为读取.JSON文件(labelme标注工具的标注文件)的点,然后将其中的点画为多边形。并保存多边形为.jpg图。保存点为txt文件。

import os
from collections import OrderedDict

import json
import cv2
import numpy as np
  
from sklearn.model_selection import train_test_split
   
def _get_json_points_ply(json_data, img_path):
    yolo_obj_list = []
    
    img_w, img_h= cv2.imread(img_path).shape[:2]
    img_b = np.array(np.zeros([img_w, img_h]))
    # draw line and write points in txt file
    with open ('Canny_edge_points.txt','w') as txt_file:
        for shape in json_data['shapes']: 
            # print(type(shape['points']))
            # print(shape['points'])
            points = np.array(shape['points']).reshape((-1,1,2))
            # draw json points to line
            cv2.polylines(img_b, [np.int32(points)], isClosed = True, color=(255,255,0), thickness=1)
            txt_file.write(" ".join(str(points)) + "\n")
    
    cv2.imwrite('./realsense/grain.jpg', img_b)
    
    cv2.namedWindow("img_b_rj_pol", cv2.WINDOW_NORMAL)
    cv2.imshow('img_b_rj_pol', img_b)

    cv2.waitKey()
    cv2.destroyAllWindows()
    
if __name__ == '__main__':  
    img_p =  './realsense/grain.png'
    json_path = './realsense/grain.json'
    json_data = json.load(open(json_path))
    _get_json_points_ply(json_data, img_p)

你可能感兴趣的:(python,polylines,.json)