【code】cv2画四坐标点图形

公众号【深度学习视觉】
第一博客

前言:4点坐标排序+画图+旋转

cv2画图

import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline

color=(255, 0, 0)
thickness=1

box = [20,30,70,30,100,50,50,50]
x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
newBox = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]]
# 如果坐标点需要排序则使用下面函数。
# newBox = sortCoordinate(box)
img = np.zeros([120, 120], dtype = np.uint8)
point = np.array(newBox).astype(int)
cv2.line(img, tuple(point[0]), tuple(point[1]), color, thickness)
cv2.line(img, tuple(point[1]), tuple(point[2]), color, thickness)
cv2.line(img, tuple(point[2]), tuple(point[3]), color, thickness)
cv2.line(img, tuple(point[3]), tuple(point[0]), color, thickness)

## 图片转三通道
image = np.expand_dims(img, axis=2)
image = np.concatenate((image, image, image), axis=-1)

# 图片显示方法二选一
matplotShow(image)
cv2Show(image)
  1. matplotShow()
  2. cv2Show()
  3. sortCoordinate()
    在这里插入图片描述

画出平行四边形所对应的矩形

def boxAngle(box):
    """
    得到旋转中心坐标,与旋转角度
    :return angle: 平行四边形转为矩形需要的角度
    :return cx, cy: 中心坐标
    """
    x1, y1, x2, y2, x3, y3, x4, y4 = box[:8]
    cx = (x1 + x3 + x2 + x4) / 4.0
    cy = (y1 + y3 + y4 + y2) / 4.0
    w = (np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + np.sqrt((x3 - x4) ** 2 + (y3 - y4) ** 2)) / 2
    h = (np.sqrt((x2 - x3) ** 2 + (y2 - y3) ** 2) + np.sqrt((x1 - x4) ** 2 + (y1 - y4) ** 2)) / 2

    sinA = (h * (x1 - cx) - w * (y1 - cy)) * 1.0 / (h * h + w * w) * 2
    angle = np.arcsin(sinA)
    
    return angle, w, h, cx, cy

angle, w, h, cx, cy = boxAngle(box)
cv2.rectangle(image, (int(cx-w/2),int(cy-h/2)), (int(cx+w/2),int(cy+h/2)), (0,255,0), 1)
# 图片显示方法二选一
matplotShow(image)
cv2Show(image)
  1. matplotShow()
  2. cv2Show()
    在这里插入图片描述

旋转平行四边形

from PIL import Image
def rotate(image,box,leftAdjustAlph=0.0,rightAdjustAlph=0.0):
    """
    需要用到boxAngle函数,得到旋转中心与旋转角度
    """
    
    angle, w, h, cx, cy = boxAngle(box)
    im = Image.fromarray(image)
    degree_ = angle*180.0/np.pi

    box = (max(1,cx-w/2-leftAdjustAlph*(w/2))##xmin
           ,cy-h/2,##ymin
           min(cx+w/2+rightAdjustAlph*(w/2),im.size[0]-1)##xmax
           ,cy+h/2)##ymax
    newW = box[2]-box[0]
    newH = box[3]-box[1]
    # 新box的信息
    box = {'cx':cx,'cy':cy,'w':newW,'h':newH,'degree':degree_,}
    
    im = im.rotate(degree_,center=(cx,cy))#.crop(box)
    
    return im

image = rotate(image,box)

# 图片显示方法二选一
matplotShow(image)
cv2Show(image)
  1. matplotShow()
  2. cv2Show()
    在这里插入图片描述
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值