【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()
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章