221 lines
6.5 KiB
Python
221 lines
6.5 KiB
Python
# -*- coding: UTF-8 -*-
|
||
#!/usr/bin/env python
|
||
# -*- encoding: utf-8 -*-
|
||
'''
|
||
@File : 多边形等距缩放.py
|
||
@data :2021/7/5 15:53
|
||
@Desciption :
|
||
@Version :
|
||
@License :
|
||
'''
|
||
|
||
import cv2
|
||
import numpy as np
|
||
import time
|
||
|
||
|
||
|
||
def contours_2_list(data):
|
||
"""将opencv读取的边界numpy数组(3个维度)转化为list(2个维度)
|
||
Args:
|
||
data为数组
|
||
|
||
|
||
Returns:
|
||
list(2个维度)
|
||
"""
|
||
# yyy = data[0]
|
||
yyy = data
|
||
# print(yyy)
|
||
list_contours = []
|
||
for i in range(yyy.shape[0]):
|
||
list_contours.append([yyy[i][0][0], yyy[i][0][1]])
|
||
return list_contours
|
||
|
||
|
||
|
||
def scale(data, sec_dis):
|
||
"""多边形等距缩放
|
||
Args:
|
||
data: 多边形按照逆时针顺序排列的的点集
|
||
sec_dis: 缩放距离
|
||
|
||
Returns:
|
||
缩放后的多边形点集
|
||
"""
|
||
num = len(data)
|
||
scal_data = []
|
||
for i in range(num):
|
||
x1 = data[(i) % num][0] - data[(i - 1) % num][0]
|
||
y1 = data[(i) % num][1] - data[(i - 1) % num][1]
|
||
x2 = data[(i + 1) % num][0] - data[(i) % num][0]
|
||
y2 = data[(i + 1) % num][1] - data[(i) % num][1]
|
||
|
||
d_A = (x1 ** 2 + y1 ** 2) ** 0.5
|
||
d_B = (x2 ** 2 + y2 ** 2) ** 0.5
|
||
|
||
Vec_Cross = (x1 * y2) - (x2 * y1)
|
||
if (d_A * d_B==0):
|
||
continue
|
||
sin_theta = Vec_Cross / (d_A * d_B)
|
||
if (sin_theta==0):
|
||
continue
|
||
dv = sec_dis / sin_theta
|
||
|
||
v1_x = (dv / d_A) * x1
|
||
v1_y = (dv / d_A) * y1
|
||
|
||
v2_x = (dv / d_B) * x2
|
||
v2_y = (dv / d_B) * y2
|
||
|
||
PQ_x = v1_x - v2_x
|
||
PQ_y = v1_y - v2_y
|
||
|
||
|
||
Q_x = data[(i) % num][0] + PQ_x
|
||
Q_y = data[(i) % num][1] + PQ_y
|
||
scal_data.append([Q_x, Q_y])
|
||
return scal_data
|
||
|
||
|
||
t1=time.time()
|
||
# 1.读入图片
|
||
# img = cv2.imread('demo/171.png')
|
||
img = cv2.imread('demo1/10.png')
|
||
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||
t2=time.time()
|
||
contours, thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
||
|
||
# 2.寻找轮廓(多边界)
|
||
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, 2)
|
||
t3=time.time()
|
||
|
||
# 3.轮廓数组转为列表(多边界)
|
||
list_contours=[]
|
||
# xxx=contours[0]
|
||
# yyy=contours[1]
|
||
|
||
for i in range(len(contours)):
|
||
list_contours.append(contours_2_list(contours[i]))
|
||
|
||
# for i in range(yyy.shape[0]):
|
||
# list_contours.append([yyy[i][0][0],yyy[i][0][1]])
|
||
|
||
data=list_contours
|
||
# 4.等距离扩大或缩小(多边界)
|
||
data1=[]
|
||
for i in range(len(data)):
|
||
data1.append(scale(data[i],-15)) #减号是往外扩
|
||
print(data1)
|
||
t4=time.time()
|
||
|
||
|
||
# 5.在原图尺寸上绘制出扩充后边界(多边界)
|
||
# temp = np.ones((img_gray.shape[0],img_gray.shape[1],3), np.uint8) * 255 #白色底图
|
||
# temp = np.zeros((img_gray.shape[0],img_gray.shape[1],3), np.uint8) * 255 #黑色底图
|
||
temp = cv2.imread('demo1/10.jpg') #原图
|
||
t5=time.time()
|
||
# cv2.polylines(temp, data1, 1, 255)
|
||
# cv2.polylines(temp,[np.array(data1, dtype=np.int32)],True, (255, 0, 0), 1,lineType=cv2.LINE_AA)
|
||
for i in range(len(data1)):
|
||
cv2.polylines(temp,[np.array(data1[i], dtype=np.int32)],True, (255, 0, 255), 5)
|
||
# cv2.polylines(temp , [np.array(data1 , dtype=np.int32)], True, (0, 0, 255), 1)\
|
||
|
||
t6=time.time()
|
||
|
||
cv2.namedWindow("boundary",cv2.WINDOW_NORMAL);
|
||
cv2.resizeWindow("boundary", 640, 480);
|
||
cv2.imshow("boundary",temp);
|
||
cv2.imwrite("demo1/24_detected.jpg",temp)
|
||
t7=time.time()
|
||
|
||
print('总耗时',t7-t1)
|
||
print("读二值图像耗时:%s 形成轮廓耗时:%s 等距离缩放耗时:%s 读取原图:%s 绘制多段线: %s 保存图像耗时:%s" %(t2-t1,t3-t2,t4-t3,t5-t4,t6-t5,t7-t6))
|
||
cv2.waitKey(0)
|
||
|
||
|
||
|
||
|
||
# import os
|
||
# from flask import Flask, request, redirect, url_for, jsonify
|
||
# from werkzeug.utils import secure_filename
|
||
#
|
||
# import cv2
|
||
# import numpy as np
|
||
#
|
||
# UPLOAD_FOLDER = './images'
|
||
# CONVERTED_FOLDER = './static'
|
||
# ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
|
||
#
|
||
# app = Flask(__name__, static_folder='static', static_url_path='/static')
|
||
# app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
|
||
# app.config['CONVERTED_FOLDER'] = CONVERTED_FOLDER
|
||
#
|
||
# def allowed_file(filename):
|
||
# return '.' in filename and \
|
||
# filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
||
#
|
||
# @app.route('/', methods=['POST'])
|
||
# def upload_file():
|
||
# if request.method == 'POST':
|
||
# if 'file' not in request.files:
|
||
# return jsonify(error = 'No file part')
|
||
# file = request.files['file']
|
||
#
|
||
# if file.filename == '':
|
||
# return jsonify(error = 'No selected file')
|
||
# if file and allowed_file(file.filename):
|
||
# filename = secure_filename(file.filename)
|
||
# file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
|
||
#
|
||
# filename_no_ext = file.filename.split('.')[0]
|
||
#
|
||
# BLUR = 21
|
||
# CANNY_THRESH_1 = 1
|
||
# CANNY_THRESH_2 = 200
|
||
# MASK_DILATE_ITER = 10
|
||
# MASK_ERODE_ITER = 10
|
||
# MASK_COLOR = (0.0,0.0,1.0)
|
||
#
|
||
# img = cv2.imread(os.path.join(app.config['UPLOAD_FOLDER'], filename))
|
||
# gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
|
||
#
|
||
# edges = cv2.Canny(gray, CANNY_THRESH_1, CANNY_THRESH_2)
|
||
# edges = cv2.dilate(edges, None)
|
||
# edges = cv2.erode(edges, None)
|
||
#
|
||
# contour_info = []
|
||
# img2, contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
|
||
# for c in contours:
|
||
# contour_info.append((
|
||
# c,
|
||
# cv2.isContourConvex(c),
|
||
# cv2.contourArea(c),
|
||
# ))
|
||
# contour_info = sorted(contour_info, key=lambda c: c[2], reverse=True)
|
||
# max_contour = contour_info[0]
|
||
#
|
||
# mask = np.zeros(edges.shape)
|
||
#
|
||
# cv2.fillConvexPoly(mask, max_contour[0], (255))
|
||
#
|
||
# mask = cv2.dilate(mask, None, iterations=MASK_DILATE_ITER)
|
||
# mask = cv2.erode(mask, None, iterations=MASK_ERODE_ITER)
|
||
# mask = cv2.GaussianBlur(mask, (BLUR, BLUR), 0)
|
||
#
|
||
#
|
||
# mask_stack = np.dstack([mask]*3)
|
||
#
|
||
# mask_stack = mask_stack.astype('float32') / 255.0
|
||
# img = img.astype('float32') / 255.0
|
||
#
|
||
# masked = (mask_stack * img) + ((1-mask_stack) * MASK_COLOR)
|
||
# masked = (masked * 255).astype('uint8')
|
||
# c_red, c_green, c_blue = cv2.split(img)
|
||
# img_a = cv2.merge((c_red, c_green, c_blue, mask.astype('float32') / 255.0))
|
||
#
|
||
# cv2.imwrite('./static/' + filename_no_ext + '.png', img_a*255)
|
||
#
|
||
# return jsonify(url = os.path.join(app.config['UPLOAD_FOLDER'],filename))
|
||
#
|
||
# app.run(host='0.0.0.0',threaded=True) |