(自己学习使用)
1. 全部代码
import json
import numpy as np
import os
from PIL import Image
import matplotlib.pyplot as plt
import cv2
'''
在图片中绘制多边形区域
'''
def process_points(im_path,points,output_path):
# 获取坐标信息,
points = np.array([points], dtype=np.int32)
# 读取图片名
img = cv2.imread(im_path)
###绘制mask
zeros = np.zeros((img.shape), dtype=np.uint8)
# # 原本thickness = -1表示内部填充,这里不知道为什么会报错,只好不填充了 改用函数cv2.polylines
#cv2.polylines(img, points, isClosed=True, thickness=5, color=(144, 238, 144))
mask = cv2.fillPoly(zeros, points, color=color_light_green) ####填充颜色
##绘制轮廓
cv2.drawContours(img, points, -1, (144, 238, 144), 5) ###绘制轮廓
##叠加mask和普通图片
mask_img = 0.3 * mask + img
##不知道为什么这里cv2.imshow会出错,可能imshow只能显示uint8格式的图片,但是将mask_img更改为mask_img.astype(np.uint8)后会出现图片失真
# cv2.imshow("handsome",mask_img.astype(np.uint8))
cv2.imwrite(os.path.join(output_path, 'handsome3.jpg'), mask_img)
'''
判断点在多边形范围内,其中pt为点,poly为多边形区域
'''
def isInsidePolygon(pt, poly):
c = False
i = -1
l = len(poly)
j = l - 1
while i < l - 1:
i += 1
#测试对应的点
# print(i, poly[i], j, poly[j])
if((poly[i][0]<=pt[0] and pt[0] < poly[j][0])or(
poly[j][0]<=pt[0] and pt[0]<poly[i][0] )):
if(pt[1]<(poly[j][1]-poly[i][1]) * (pt[0]-poly[i][0])/(
poly[j][0]-poly[i][0])+poly[i][1]):
c = not c
j=i
return c
if __name__ == '__main__':
# 这是我用labelme画的不规则点坐标,作为多边形轮廓中的点
points=[
[
345.54237288135596,
198.4576271186441
],
[
348.93220338983053,
339.135593220339
],
[
382.8305084745763,
496.7627118644068
],
[
404.86440677966107,
581.5084745762712
],
[
428.5932203389831,
642.5254237288136
],
[
547.2372881355933,
652.6949152542373
],
[
911.6440677966102,
637.4406779661017
],
[
1338.7627118644068,
539.135593220339
],
[
1608.2542372881358,
476.42372881355936
],
[
1662.491525423729,
451.0
],
[
1572.6610169491526,
378.1186440677966
],
[
1631.9830508474577,
303.54237288135596
],
[
1748.9322033898306,
298.4576271186441
],
[
1831.9830508474577,
289.98305084745766
],
[
1772.6610169491526,
176.42372881355936
],
[
389.6101694915254,
198.4576271186441
]
]
color_light_yellow=(0, 165, 255) ##浅黄色
color_light_green=(144, 238, 144) ##浅绿色
pt_u = [794, 295] ##随机的点1
pt_d = [794, 297] #随机的点2
print(isInsidePolygon(pt_u,points))##判断点1在不在多边形闭合区域内
print(isInsidePolygon(pt_d,points))## 判断点2 在不在多边形闭合区域内
process_points(im_path=r'D:\pyproject\biye\pic_biye\csdn3.jpg',points=points,output_path='./')
2. List item
缺少的模块自行添加即可
4.输出结果
输出图片
D:\allsoft\study\anaconda\envs\test1\python.exe D:/pyproject/biye/计算机大赛/判断点在不在区域内,上传csdn.py
True
True
进程已结束,退出代码0
有帮助的或者感兴趣的可以点个关注,一起交流关于图像处理或深度学习的知识。