zoukankan      html  css  js  c++  java
  • Opencv 拼接图片

    Opencv 拼接图片

     读取文件夹下图片,并拼接图片
    

    代码示例

    #!/usr/bin/env python3
    # -*- coding: UTF-8 -*-
    
    
    import cv2
    import numpy as np
    import os
    import os.path
    
    
    def imgmatrix_from_dir(path):
        """将图像存储到矩阵内"""
        shape_x, shape_y = 256, 144
        img_nms = [img_name for img_name in os.listdir(path) if img_name.upper().endswith("JPG")]
        print(len(img_nms))
        image_arr = cv2.resize(cv2.imread(os.path.join(path, img_nms[0]), flags=cv2.IMREAD_COLOR), (shape_x, shape_y))
        print(image_arr.size)
        print(image_arr.shape)
        for index, img_nm in enumerate(img_nms):
            image1 = cv2.resize(cv2.imread(os.path.join(path, img_nm), flags=cv2.IMREAD_COLOR), (shape_x, shape_y))
            if image1 is not None:
                # 数组拼接
                #img = np.vstack((img, img2))  # vstack按垂直方向,hstack按水平方向
                image_arr = np.concatenate((image_arr, image1), axis=1)
        # 数组切片
        return image_arr[:,shape_x:,:]
    
    
    if __name__ == '__main__':
        img_dir = r"F:	te	estmix"
        img_martix = imgmatrix_from_dir(img_dir)
        print(img_martix)
        print(img_martix.size)
        print(img_martix.shape)
        cv2.imwrite(os.path.join(img_dir,"res.jpg"), img_martix)
    

    对图形矩阵做变换

     将二维的图像数据变为一维的图像数据
     将三维的图像变为一维的图像数据,然后将多张图片拼接起来,就成为了以一维图片数据为每行是一张图片,多行就是多张图片 image1.reshape(1, -1)
    

    代码示例

    def img_matrix_from_dir(path):
        """返回二维矩阵"""
        shape_x, shape_y = 256, 144
        img_nms = [img_name for img_name in os.listdir(path) if img_name.upper().endswith("JPG")]
        print(len(img_nms))
        # 灰度图
        input_color = cv2.IMREAD_GRAYSCALE
        img_nm_list = []
        image_arr = cv2.resize(cv2.imread(os.path.join(path, img_nms[0]), flags=input_color), (shape_x, shape_y))
        image_arr = image_arr.reshape(1, -1)
        for index, img_nm in enumerate(img_nms):
            image1 = cv2.resize(cv2.imread(os.path.join(path, img_nm), flags=input_color), (shape_x, shape_y))
            # 指定行数,那么列数直接用-1代替就行了-它代表任意整数-原数据有多少列就有多少列
            image1 = image1.reshape(1, -1)
            if image1 is not None:
                # 数组拼接
                #img = np.vstack((img, img2))  # vstack按垂直方向,hstack按水平方向
                image_arr = np.concatenate((image_arr, image1), axis=0)
                img_nm_list.append(img_nm)
        # 数组切片-移除重复的第一张图片
        return image_arr[1:, :], img_nm_list
    

    对image_matrix 机器学习

    #pipeline 与深度神经网络的multi-layers
    #pipeline 实现了对全部步骤的流式化封装和管理(streaming workflows with pipelines)
    
    from sklearn.decomposition import PCA
    from sklearn.cluster import KMeans, MiniBatchKMeans
    from sklearn.pipeline import Pipeline
    from sklearn.model_selection import GridSearchCV
    img_matrix=""
    # 格式为('key','value'),key是自己为这一step设定的名称,value是对应的处理类
    pipe_cluster = Pipeline(steps=[('pca', PCA(n_components=2)),
                                   ('kmeans',  KMeans(n_clusters=3, max_iter=10))]
                       , memory=None, verbose=False)
    print(pipe_cluster.steps[0])
    print(pipe_cluster.named_steps['pca'])
    #  set_params重新设置每个类里边需传入的参数,设置方法为step的name__parma名=参数值
    #修改参数并打印输出 name__parma名=参数值
     print(pipe.set_params(pca_n_components=10))	
    #训练和预测 
    pipe_cluster.fit(img_matrix)
    y_predict = pipe_cluster.predict(img_matrix)
    print(y_predict)
    
    # 超参数自动搜索模块 GridSearchCV
    # 网格搜索算法是一种通过遍历给定的参数组合来优化模型表现的方法
    # K折交叉验证
    params = dict(pca__n_components=[2, 5, 10], kmeans__n_clusters=[0, 1, 10, 100])
    grid_research = GridSearchCV(estimator=pipe_cluster, param_grid=params, scoring=None, cv=None)
    
    
    #make_pipeline函数实现:
    #它是Pipeline类的简单实现,只需传入每个step的类实例即可,不需自己命名,自动将类的小写设为该step的名
    #同时可以通过set_params重新设置每个类里边需传入的参数,设置方法为step的name__parma名=参数值
    #"Pipeline", "FeatureUnion", "make_pipeline", "make_union"
    

    K-means算法

    K-means使用的欧式距离
        01.随机初始点不好并且不知道初始中心点数量的问题, 引入 K-means++
        02.   
           一个是传统的      K-Means             算法,对应的类是 KMeans 
           另一个是基于采样的 Mini Batch K-Means 算法,对应的类是 MiniBatchKMeans
      
    K-modes是K-means用在非数值集合上的一种方法,使用字符间的汉明距离
    K-prototype 是处理混合属性聚类的典型算法。继承Kmean算法和Kmode算法的思想
        并且加入了描述数据簇的原型和混合属性数据之间的相异度计算公式
        混合属性中存在数值属性和分类属性,其原型的定义是
          数值属性原型用属性中所有属性取值值的均值,
    	 分列属性原型是分类属性中选取属性值取值频率最高的属性。合起来就是原型
    	相异度距离: 
    	   一般来说,数值属性的相异度一般选用欧式距离,。
           对于分类属性:使用海明威距离,即属性值相同,为0 ;属性值不同,为1
    	   在K-prototype算法中混合属性的相异度分为属性属性和分类属性分开求,然后相加
    	目标函数
    改变K-means对异常值的敏感情况,引入K-medoids算法
    

    参考

     Python之Numpy数组拼接,组合,连接 https://www.cnblogs.com/huangshiyu13/p/6672828.html
     Python高级特性——详解多维数组切片(Slice)  https://www.jb51.net/article/175155.htm
     numpy和cv2.imread( )中三维数组位置详解  https://blog.csdn.net/qq_37233260/article/details/119337233
     sklearn-kmeans 人脸图像聚类 https://www.pythonheidong.com/blog/article/341231/b261232dae750c04bcdd/
      result = result.reshape(210, 200, 180, 3)#图像的矩阵大小为200,180,3   210张,矩阵大小是()shape+channel
     怎样用python进行K-means图片聚类 https://www.it610.com/article/1288481894446473216.htm
       sklearn 中的 Pipeline 机制 和FeatureUnion  https://www.cnblogs.com/nolonely/p/6970419.html
  • 相关阅读:
    Atitit..组件化事件化的编程模型(2)Web datagridview 服务器端控件的实现原理and总结
    Atitit.dwr3 不能显示错误详细信息的解决方案,控件显示错误详细信息的解决方案 java .net php
    Atitit.实现继承的原理and方法java javascript .net c# php ...
    Atitit. 解压缩zip文件 的实现最佳实践 java c# .net php
    Atitit..文件上传组件选型and最佳实践总结(2)断点续传
    atitit.web的动态include 跟变量传递 java .net php
    Atitit. BigConfirmTips 控件 大数据量提示确认控件的原理and总结O9
    Atitit.guice3 ioc 最佳实践 o9o
    Atitit.hybrid混合型应用 浏览器插件,控件的实现方式 浏览器运行本地程序的解决方案大的总结提升用户体验and开发效率..
    atitit.提升开发效率使用服务器控件生命周期 asp.net 11个阶段 java jsf 的6个阶段比较
  • 原文地址:https://www.cnblogs.com/ytwang/p/15421482.html
Copyright © 2011-2022 走看看