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

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

例如

 

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

特别注意不是:

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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值