4.2 比多数opencv函数效果更好的二值化(python)

2024-03-07 04:12

本文主要是介绍4.2 比多数opencv函数效果更好的二值化(python),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里之间写代码:

import numpy as np
import torch
import torch.nn as nn
import cv2#1.silu激活函数
class SiLU(nn.Module):@staticmethoddef forward(x):return x*torch.sigmoid(x)#2.获得轨道的类
def railway_classes3(img,x1,x2,y1,y2):img2 = img[x1:x2, y1:y2, :]return img2class Conv(nn.Module):def __init__(self):super(Conv, self).__init__()#标准化加激活函数self.bn     = nn.BatchNorm2d(3)#标准化self.act    = SiLU()def forward(self,x):#x=self.conv(x)x=self.bn(x)x= self.act(x)return xif __name__ == "__main__":#输入图片路径image=cv2.imread(r"imgs/000002.jpg")img2=railway_classes3(image, x1=640, x2=740, y1=825, y2=1025)cv2.imshow("ss",img2)cv2.waitKey(0)cv2.imwrite("imgs/00.jpg",img2)images = img2.reshape(1, 3, img2.shape[0], img2.shape[1])data = torch.tensor(images)datas = torch.tensor(images, dtype=torch.float32)sp=Conv()output=sp(datas)ar=output.detach().numpy()result=ar.reshape(img2.shape[0], img2.shape[1],3)print(result)#图片处理for i in range(result.shape[0]):for j in range(1,result.shape[1]-2):ss1 = result[i, j - 1:j + 2,:].mean()m = result[i][j].mean() - ss1if m >= ss1:print(ss1)img2[i][j] = 255else:img2[i][j] = 0img2[:, -3:] = 0img2[:, :3] = 0cv2.imshow("ss", img2)cv2.waitKey(0)

处理效果如下:

第一张光线比较强的图片:

                                                    原图                                   二值化图

第二张光线比较暗的图

原图                                   二值化图

        以上图片处理的方式用了BatchNorm处理和Xsilu处理,最后感觉这种效果还可以,尤其是在强光下的效果。

2.用普通的计算方法代码如下:

import numpy as np
import cv2
import time
import oscolors = [ (0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128),(128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0), (192, 128, 0), (64, 0, 128), (192, 0, 128),(64, 128, 128), (192, 128, 128), (0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0), (0, 64, 128),(128, 64, 12)]def cluster(points, radius=100):"""points: pointcloudradius: max cluster range"""print("................", len(points))items = []while len(points)>1:item = np.array([points[0]])base = points[0]points = np.delete(points, 0, 0)distance = (points[:,0]-base[0])**2+(points[:,1]-base[1])**2#获得距离infected_points = np.where(distance <= radius**2)#与base距离小于radius**2的点的坐标item = np.append(item, points[infected_points], axis=0)border_points = points[infected_points]points = np.delete(points, infected_points, 0)while len(border_points) > 0:border_base = border_points[0]border_points = np.delete(border_points, 0, 0)border_distance = (points[:,0]-border_base[0])**2+(points[:,1]-border_base[1])**2border_infected_points = np.where(border_distance <= radius**2)#print("/",border_infected_points)item = np.append(item, points[border_infected_points], axis=0)if len(border_infected_points)>0:for k in border_infected_points:if points[k] not in border_points:border_points=np.append(border_points,points[k], axis=0)#border_points = points[border_infected_points]points = np.delete(points, border_infected_points, 0)items.append(item)return items#2.获得轨道的类
def railway_classes(img,x1,x2,y1,y2):img2 = img[x1:x2, y1:y2, :]  # [540:741, 810:1080],截取轨道画线的区域,对该区域识别轨道print("img2:", img2.shape)dst = np.zeros((img2.shape[0], img2.shape[1]), np.uint8)for i in range(img2.shape[0]):for j in range(2, img2.shape[1] - 2):z = img2[i, j - 2:j + 2]# print(z)a_z = np.average(z, axis=0)  # 按列求均值# print(a_z)m = abs(img2[i][j] - a_z).max()# print(m)if m > 12:dst[i][j] = 255else:dst[i][j] = 0cv2.imshow("ss", dst)cv2.waitKey(0)img2=dst# cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\170.jpg", img2)# 3.腐蚀膨胀消除轨道线外的点kernel = np.uint8(np.ones((5, 1)))# 膨胀图像.....为了使得轨道线更粗,且补足轨道线缺失的地方dilated = cv2.dilate(img2, kernel)kernel = np.ones((2, 3), np.uint8)dilated = cv2.erode(dilated, kernel)#ss=np.argwhere(dilated >0)#dilated# cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\120.jpg",dilated)cv2.imshow("ss", dilated)cv2.waitKey(0)#聚类算法t1=time.time()items = cluster(ss, radius=3)i=0out=[]#获得大于300个坐标的类for item in items:if len(item)>180:out.append(item)for k in item:img[k[0]+x1][k[1]+y1]=colors[i]i+=1t2=time.time()print("dbscan消耗时间:",t2-t1)cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\0.jpg", img)return out#2.获得轨道的类
def railway_classes2(img,x1,x2,y1,y2):img2 = img[x1:x2, y1:y2, :]  # [540:741, 810:1080],截取轨道画线的区域,对该区域识别轨道print("img2:", img2.shape)dst = np.zeros((img2.shape[0], img2.shape[1]), np.uint8)for i in range(img2.shape[0]):for j in range(2, img2.shape[1] - 2):z = img2[i, j - 2:j + 2]# print(z)a_z = np.average(z, axis=0)  # 按列求均值# print(a_z)m = abs(img2[i][j] - a_z).max()# print(m)if m > 12:dst[i][j] = 255else:dst[i][j] = 0cv2.imshow("ss", dst)cv2.waitKey(0)img2=dst# cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\170.jpg", img2)# 3.腐蚀膨胀消除轨道线外的点kernel = np.uint8(np.ones((5, 1)))# 膨胀图像.....为了使得轨道线更粗,且补足轨道线缺失的地方dilated = cv2.dilate(img2, kernel)kernel = np.ones((2, 3), np.uint8)dilated = cv2.erode(dilated, kernel)#ss=np.argwhere(dilated >0)#dilated# cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\120.jpg",dilated)cv2.imshow("ss", dilated)cv2.waitKey(0)#聚类算法t1=time.time()items = cluster(ss, radius=3)i=0out=[]#获得大于300个坐标的类for item in items:if len(item)>80:out.append(item)for k in item:img[k[0]+x1][k[1]+y1]=colors[i]i+=1t2=time.time()print("dbscan消耗时间:",t2-t1)cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\0.jpg", img)return out#2.获得轨道的类
def railway_classes3(img,x1,x2,y1,y2):img2 = img[x1:x2, y1:y2, :]  # [540:741, 810:1080],截取轨道画线的区域,对该区域识别轨道print("img2:", img2.shape)dst = np.zeros((img2.shape[0], img2.shape[1]), np.uint8)for i in range(img2.shape[0]):for j in range(2, img2.shape[1] - 2):z = img2[i, j - 2:j + 2]# print(z)a_z = np.average(z, axis=0)  # 按列求均值# print(a_z)m = abs(img2[i][j] - a_z).max()# print(m)if m > 11:dst[i][j] = 255else:dst[i][j] = 0cv2.imshow("ss", dst)cv2.waitKey(0)img2=dst# cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\170.jpg", img2)# # 3.腐蚀膨胀消除轨道线外的点kernel = np.uint8(np.ones((4, 2)))# 膨胀图像.....为了使得轨道线更粗,且补足轨道线缺失的地方dilated = cv2.dilate(img2, kernel)kernel = np.ones((3, 3), np.uint8)dilated = cv2.erode(dilated , kernel)# ## kernel = np.uint8(np.ones((5, 2)))# # 膨胀图像.....为了使得轨道线更粗,且补足轨道线缺失的地方# dilated = cv2.dilate(dilated, kernel)ss=np.argwhere(dilated >0)#dilated# cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\120.jpg",dilated)cv2.imshow("ss", dilated)cv2.waitKey(0)#聚类算法t1=time.time()items = cluster(ss, radius=3)i=0out=[]#获得大于300个坐标的类for item in items:if len(item)>80:out.append(item)for k in item:img[k[0]+x1][k[1]+y1]=colors[i]i+=1t2=time.time()print("dbscan消耗时间:",t2-t1)cv2.imwrite("D:\AI\project\eye_hand_biaoding\\railways\dbscan\img\\0.jpg", img)return out#以15个左右的像素点,将类每个类分为很多个小类画直线
def fenlei(classes,num):class_mean=[]for item in classes:item_classes=[]#获取初始点的值hh=item[:5]y=hh[0][0]x=int(hh[:,-1:].mean())item_classes.append((x, y))item =item[item[:,0].argsort()]#对数据分成很多个段,再while len(item) > num+15:items=item[:num]s1=itemsy10=int(s1[:, :1].mean())x10=int(s1[:,-1:].mean())item_classes.append((x10,y10))item=item[120:]if len(item)>5:s1 = itemy10 = int(s1[:, :1].mean())x10 = int(s1[:, -1:].mean())item_classes.append((x10, y10))class_mean.append(item_classes)all_k=[]for item in class_mean:k_b=[]for i in range(len(item)-1):x10,y10=item[i][0],item[i][1]x20, y20 = item[i+1][0], item[i+1][1]k1=(y10-y20)/(x10-x20+0.00001)b1=y10-k1*x10k_b.append((k1, b1, [y10,y20]))all_k.append(k_b)print(all_k)return all_k#画线
def draw_line(img,all_k,x1,x2,y1,y2):print("......................画直线.............................")for k_b in all_k:ss=np.array(k_b)ks=np.array(ss[:,:1]/len(ss)).sum()*0.5#print(ks)for i in range(len(k_b)):k, b, (y10, y20) = k_b[i]x10 = int((y10 - b) / (k+0.000001))x20 = int((y20 - b) / (k+0.000001))cv2.line(img, (x10 + y1, y10 + x1), (x20 + y1, y20 + x1), (0, 0, 255), 2)cv2.imshow("line_detect_possible_demo", img)cv2.waitKey(0)if __name__ == '__main__':start=time.time()img_paths = r"imgs\000004.jpg"save_paths = r"imgs\20.jpg"img = cv2.imread(img_paths)img2=img.copy()all_class = {}all_class["1"] = []all_class["2"] = []# 第1次*************************************************************************************#获得轨道的类classes=railway_classes(img,  x1=680, x2=740, y1=825, y2=1045)## 求第一段的类all_class["1"].append(classes[0])all_class["2"].append(classes[1])start1 = classes[0][:20, 1:].mean() + 825start2 = classes[1][:20, 1:].mean() + 825print(start1, start2)#=============================================================================================================# classes2 = railway_classes2(img, x1=640, x2=680, y1=845, y2=995)  ## print("......................................................")# # 求第一段的类# for item in classes2:#     # print("start===>",item[:20,1:].mean()+845)#     # print("end===>",item[-20:,1:].mean()+845)#     if abs((item[-20:, 1:].mean() + 845) - start1) < 10:#         np.vstack((all_class["1"][0], item))#         start1 = item[:20, 1:].mean() + 845#     elif abs((item[-20:, 1:].mean() + 845) - start2) < 10:#         np.vstack((all_class["2"][0], item))#         start2 = item[:20, 1:].mean() + 845# print(start1, start2)## # =============================================================================================================# classes3 = railway_classes3(img, x1=610, x2=640, y1=855, y2=965)  ## print("......................................................")# for item in classes3:#     # print("start===>",item[:,1:].mean()+855)#     # print("end===>", item[-20:, 1:].mean() + 855)#     if abs((item[-20:, 1:].mean() + 855) - start1) < 10:#         np.vstack((all_class["1"][0], item))#         start1 = item[:20, 1:].mean() + 855#     elif abs((item[-20:, 1:].mean() + 855) - start2) < 10:#         np.vstack((all_class["2"][0], item))#         start2 = item[:20, 1:].mean() + 855# print(start1, start2)ss=[]ss.append(all_class["1"][0])ss.append(all_class["2"][0])print(ss[0])# 以15个左右的像素点,将类每个类分为很多个小类画直线num=100all_k=fenlei(ss,num)#classes## # 画线draw_line(img, all_k, x1=680, x2=740, y1=825, y2=1035)#

这篇关于4.2 比多数opencv函数效果更好的二值化(python)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/782338

相关文章

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

Python 中的异步与同步深度解析(实践记录)

《Python中的异步与同步深度解析(实践记录)》在Python编程世界里,异步和同步的概念是理解程序执行流程和性能优化的关键,这篇文章将带你深入了解它们的差异,以及阻塞和非阻塞的特性,同时通过实际... 目录python中的异步与同步:深度解析与实践异步与同步的定义异步同步阻塞与非阻塞的概念阻塞非阻塞同步

Python Dash框架在数据可视化仪表板中的应用与实践记录

《PythonDash框架在数据可视化仪表板中的应用与实践记录》Python的PlotlyDash库提供了一种简便且强大的方式来构建和展示互动式数据仪表板,本篇文章将深入探讨如何使用Dash设计一... 目录python Dash框架在数据可视化仪表板中的应用与实践1. 什么是Plotly Dash?1.1

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

Python下载Pandas包的步骤

《Python下载Pandas包的步骤》:本文主要介绍Python下载Pandas包的步骤,在python中安装pandas库,我采取的方法是用PIP的方法在Python目标位置进行安装,本文给大... 目录安装步骤1、首先找到我们安装python的目录2、使用命令行到Python安装目录下3、我们回到Py

Python GUI框架中的PyQt详解

《PythonGUI框架中的PyQt详解》PyQt是Python语言中最强大且广泛应用的GUI框架之一,基于Qt库的Python绑定实现,本文将深入解析PyQt的核心模块,并通过代码示例展示其应用场... 目录一、PyQt核心模块概览二、核心模块详解与示例1. QtCore - 核心基础模块2. QtWid

Python实现自动化接收与处理手机验证码

《Python实现自动化接收与处理手机验证码》在移动互联网时代,短信验证码已成为身份验证、账号注册等环节的重要安全手段,本文将介绍如何利用Python实现验证码的自动接收,识别与转发,需要的可以参考下... 目录引言一、准备工作1.1 硬件与软件需求1.2 环境配置二、核心功能实现2.1 短信监听与获取2.

使用Python实现获取网页指定内容

《使用Python实现获取网页指定内容》在当今互联网时代,网页数据抓取是一项非常重要的技能,本文将带你从零开始学习如何使用Python获取网页中的指定内容,希望对大家有所帮助... 目录引言1. 网页抓取的基本概念2. python中的网页抓取库3. 安装必要的库4. 发送HTTP请求并获取网页内容5. 解

利用Python开发Markdown表格结构转换为Excel工具

《利用Python开发Markdown表格结构转换为Excel工具》在数据管理和文档编写过程中,我们经常使用Markdown来记录表格数据,但它没有Excel使用方便,所以本文将使用Python编写一... 目录1.完整代码2. 项目概述3. 代码解析3.1 依赖库3.2 GUI 设计3.3 解析 Mark

一文教你Python引入其他文件夹下的.py文件

《一文教你Python引入其他文件夹下的.py文件》这篇文章主要为大家详细介绍了如何在Python中引入其他文件夹里的.py文件,并探讨几种常见的实现方式,有需要的小伙伴可以根据需求进行选择... 目录1. 使用sys.path动态添加路径2. 使用相对导入(适用于包结构)3. 使用pythonPATH环境