首页 > 编程语言 >Python停车场车位识别

Python停车场车位识别

时间:2024-10-22 18:48:08浏览次数:3  
标签:Python image cv2 self 停车场 blog avg 车位

程序示例精选
Python停车场车位识别
如需安装运行环境或远程调试,见文章底部个人QQ名片,由专业技术人员远程协助!

前言

这篇博客针对《Python停车场车位识别》编写代码,代码整洁,规则,易读。 学习与应用推荐首选。


文章目录

一、所需工具软件
二、使用步骤
       1. 主要代码
       2. 运行结果
三、在线协助

一、所需工具软件

       1. Python
       2. Pycharm

二、使用步骤

代码如下(示例):

import matplotlib.pyplot as plt
import cv2
import os, glob
import numpy as np



class Parking:
    
    def show_images(self, images, cmap=None):
        cols = 2
        rows = (len(images)+1)//cols
        
        plt.figure(figsize=(15, 12))
        for i, image in enumerate(images):
            plt.subplot(rows, cols, i+1)
            cmap = 'gray' if len(image.shape)==2 else cmap
            plt.imshow(image, cmap=cmap)
            plt.xticks([])
            plt.yticks([])
        plt.tight_layout(pad=0, h_pad=0, w_pad=0)
        plt.show()
    
    def cv_show(self,name,img):
        cv2.imshow(name, img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    def select_rgb_white_yellow(self,image): 
        #过滤掉背景
        lower = np.uint8([120, 120, 120])
        upper = np.uint8([255, 255, 255])
        # lower_red和高于upper_red的部分分别变成0,lower_red~upper_red之间的值变成255,相当于过滤背景
        white_mask = cv2.inRange(image, lower, upper)
        self.cv_show('white_mask',white_mask)
        
        masked = cv2.bitwise_and(image, image, mask = white_mask)
        self.cv_show('masked',masked)
        return masked
    def convert_gray_scale(self,image):
        return cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    def detect_edges(self,image, low_threshold=50, high_threshold=200):
        return cv2.Canny(image, low_threshold, high_threshold)
    
    def filter_region(self,image, vertices):
        """
                剔除掉不需要的地方
        """
        mask = np.zeros_like(image)
        if len(mask.shape)==2:
            cv2.fillPoly(mask, vertices, 255)
            self.cv_show('mask', mask)    
        return cv2.bitwise_and(image, mask)
    
    def select_region(self,image):
        """
                手动选择区域
        """
        # first, define the polygon by vertices
        rows, cols = image.shape[:2]
        pt_1  = [cols*0.05, rows*0.90]
        pt_2 = [cols*0.05, rows*0.70]
        pt_3 = [cols*0.30, rows*0.55]
        pt_4 = [cols*0.6, rows*0.15]
        pt_5 = [cols*0.90, rows*0.15] 
        pt_6 = [cols*0.90, rows*0.90]

        vertices = np.array([[pt_1, pt_2, pt_3, pt_4, pt_5, pt_6]], dtype=np.int32) 
        point_img = image.copy()       
        point_img = cv2.cvtColor(point_img, cv2.COLOR_GRAY2RGB)
        for point in vertices[0]:
            cv2.circle(point_img, (point[0],point[1]), 10, (0,0,255), 4)
        self.cv_show('point_img',point_img)
        
        
        return self.filter_region(image, vertices)
    
    def hough_lines(self,image):
        #输入的图像需要是边缘检测后的结果
        #minLineLengh(线的最短长度,比这个短的都被忽略)和MaxLineCap(两条直线之间的最大间隔,小于此值,认为是一条直线)
        #rho距离精度,theta角度精度,threshod超过设定阈值才被检测出线段
        return cv2.HoughLinesP(image, rho=0.1, theta=np.pi/10, threshold=15, minLineLength=9, maxLineGap=4)
        
    def draw_lines(self,image, lines, color=[255, 0, 0], thickness=2, make_copy=True):
        # 过滤霍夫变换检测到直线
        if make_copy:
            image = np.copy(image) 
        cleaned = []
        for line in lines:
            for x1,y1,x2,y2 in line:
                if abs(y2-y1) <=1 and abs(x2-x1) >=25 and abs(x2-x1) <= 55:
                    cleaned.append((x1,y1,x2,y2))
                    cv2.line(image, (x1, y1), (x2, y2), color, thickness)
        print(" No lines detected: ", len(cleaned))
        return image
    def identify_blocks(self,image, lines, make_copy=True):
        if make_copy:
            new_image = np.copy(image)
        #Step 1: 过滤部分直线
        cleaned = []
        for line in lines:
            for x1,y1,x2,y2 in line:
                if abs(y2-y1) <=1 and abs(x2-x1) >=25 and abs(x2-x1) <= 55:
                    cleaned.append((x1,y1,x2,y2))
        
        #Step 2: 对直线按照x1进行排序
        import operator
        list1 = sorted(cleaned, key=operator.itemgetter(0, 1))
        
        #Step 3: 找到多个列,相当于每列是一排车
        clusters = {}
        dIndex = 0
        clus_dist = 10
    
        for i in range(len(list1) - 1):
            distance = abs(list1[i+1][0] - list1[i][0])
            if distance <= clus_dist:
                if not dIndex in clusters.keys(): clusters[dIndex] = []
                clusters[dIndex].append(list1[i])
                clusters[dIndex].append(list1[i + 1]) 
    
            else:
                dIndex += 1
        
        #Step 4: 得到坐标
        rects = {}
        i = 0
        for key in clusters:
            all_list = clusters[key]
            cleaned = list(set(all_list))
            if len(cleaned) > 5:
                cleaned = sorted(cleaned, key=lambda tup: tup[1])
                avg_y1 = cleaned[0][1]
                avg_y2 = cleaned[-1][1]
                avg_x1 = 0
                avg_x2 = 0
                for tup in cleaned:
                    avg_x1 += tup[0]
                    avg_x2 += tup[2]
                avg_x1 = avg_x1/len(cleaned)
                avg_x2 = avg_x2/len(cleaned)
                rects[i] = (avg_x1, avg_y1, avg_x2, avg_y2)
                i += 1
        
        print("Num Parking Lanes: ", len(rects))
        #Step 5: 把列矩形画出来
        buff = 7
      
    
                cv2.putText(new_image, "Available: %d spots" %cnt_empty, (30, 95),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.7, (255, 255, 255), 2)
    
                cv2.putText(new_image, "Total: %d spots" %all_spots, (30, 125),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.7, (255, 255, 255), 2)
                cv2.imshow('frame', new_image)
                if cv2.waitKey(10) & 0xFF == ord('q'):
                    break

        cv2.destroyAllWindows()
        cap.release()


运行结果

三、在线协助:

如需安装运行环境或远程调试,见文章底部个人 QQ 名片,由专业技术人员远程协助!

1)远程安装运行环境,代码调试
2)Visual Studio, Qt, C++, Python编程语言入门指导
3)界面美化
4)软件制作
5)云服务器申请
6)网站制作

当前文章连接:https://blog.csdn.net/alicema1111/article/details/132666851
个人博客主页https://blog.csdn.net/alicema1111?type=blog
博主所有文章点这里:https://blog.csdn.net/alicema1111?type=blog

博主推荐:
Python人脸识别考勤打卡系统:
https://blog.csdn.net/alicema1111/article/details/133434445
Python果树水果识别https://blog.csdn.net/alicema1111/article/details/130862842
Python+Yolov8+Deepsort入口人流量统计:https://blog.csdn.net/alicema1111/article/details/130454430
Python+Qt人脸识别门禁管理系统:https://blog.csdn.net/alicema1111/article/details/130353433
Python+Qt指纹录入识别考勤系统:https://blog.csdn.net/alicema1111/article/details/129338432
Python Yolov5火焰烟雾识别源码分享:https://blog.csdn.net/alicema1111/article/details/128420453
Python+Yolov8路面桥梁墙体裂缝识别:https://blog.csdn.net/alicema1111/article/details/133434445
Python+Yolov5道路障碍物识别:https://blog.csdn.net/alicema1111/article/details/129589741
Python+Yolov5跌倒检测 摔倒检测 人物目标行为 人体特征识别:https://blog.csdn.net/alicema1111/article/details/129272048

标签:Python,image,cv2,self,停车场,blog,avg,车位
From: https://blog.csdn.net/alicema1111/article/details/143078660

相关文章

  • python 轻松实现公司内部音视频会议
     一些公司内部会议系统价格比较昂贵,而且经常出现问题,为了保证公司内部数据泄密问题,可以自己开发一个内部视频会议软件。会议窗口如下开发语言        python3.9功能描述:        python实现公司内部音视频会议、收发文件实现代码(简易版)     ......
  • Python学习的自我理解和想法(19)
    #1024程序员节|征文#学的是b站的课程(千锋教育),跟老师写程序,不是自创的代码!今天是学Python的第19天,学的内容是面向对象。开学了,时间不多,写得不多,见谅。目录1.面向对象的三大特性(1).封装(2).继承(3).多态2.继承(1).简单使用(2).有构造函数的继承1.继承父类的构造方法......
  • COP3502 P2: RLE with Images Python
    COP3502P2:RLEwithImagesPythonOverviewInthisprojectstudentswilldeveloproutinestoencodeanddecodedataforimagesusingrun-lengthencodingRLE).Studentswillimplementencodinganddecodingofrawdata,conversionbetweendataandstring......
  • Python基础学习目录
    Python学习目录Python自动化第一周Python自动化第二周Python文件的操作Python函数的进阶Python装饰器Python函数基础Python深浅copyPython迭代器、生成器Python推导式Python内置函数及匿名函数Python递归及二分查找算法Python面向对象(基础篇)Pytho......
  • 004 Python数据类型
    1#int可以将纯整数构成的字符串转换成整型,若包含其它非整数符号则会报错2s='123'3res=int(s)4print(res,type(res))56#s='12.3'7#res=int(s)8#print(res,type(s))910#十进制与其它进制之间的相互转换11#十进制转其它进制12print......
  • [Python] Selenium监控网络请求
      Selenium监控网络有两种方式,第一种使用代理,第二张是使用CDP(ChromeDevToolsProtocol)协议,下面直接进入主题分别介绍如何使用代理和CDP协议监控网络请求。  一、使用Selenium-Wire设置代理拦截处理请求。  Selenium-Wire是基于Selenium开发的抓包工具,基本使用方式如下:fr......
  • python第六章课后习题
    点击查看代码print("学号:2023310143028")点击查看代码defprim(graph,start):num_nodes=len(graph)visited=[False]*num_nodesmin_heap=[(0,start,-1)]mst_cost=0mst_edges=[]whilemin_heap:......
  • Python 数据分析与可视化有什么区别
    在当今的数据驱动时代,Python已成为数据分析和数据可视化的重要工具。尽管这两个领域经常在数据科学项目中相互交织,但它们在功能和目的上存在本质区别。本文旨在详细探讨Python在数据分析和数据可视化方面的差异,包括它们的定义、使用的主要库、应用场景以及在实际项目中的作用。通......
  • python第四章课后习题
    点击查看代码importnumpyasnpimportcvxpyascpx=cp.Variable(6,pos=True)obj=cp.Minimize(x[5])a1=np.array([0.025,0.015,0.055,0.026])a2=np.array([0.05,0.27,0.19,0.185,0.185])a3=np.array([1,1.01,1.02,1.045,1.065])k=0.05;kk=[];qq=[]whil......
  • Python教程:Python父类方法重写
    在Python中,子类可以通过定义与父类同名的方法来重写(Override)父类的方法。这种机制允许子类提供特定的实现,以替代从父类继承的通用实现。重写父类方法时,子类方法将覆盖父类方法的行为,但子类仍然可以访问父类方法的原始实现(如果需要的话)。以下是一个简单的示例,展示了如何在Py......