欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

opencv-python图像预处理记录

程序员文章站 2022-07-13 08:53:11
...

1.

        image_array = cv2.imread(img_name, -1)
        if image_array.ndim == 2:
            image_array = cv2.cvtColor(image_array, cv2.COLOR_GRAY2BGR)
        image = Image.fromarray(image_array.astype('uint8')).convert('RGB')

空数组 最重要的还是shape=(0,5),其实ones也可以

temp = np.empty(shape=(0,5), dtype=np.float32)

关于空数组的使用,参考某一段代码:

出自github项目hpatches-benchmark

from utils.hpatch import *
import cv2
import os.path


# all types of patches
tps = ['ref','e1','e3','e5','h1','h3','h5','t1','t3','t5']
datadir = '/home/boyun/deepglint/ImageMatch_dataset/data'
#datadir = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "data"))

def vis_patches(seq,tp,ids):
    """Visualises a set of types and indices for a sequence"""
    h = len(tp)*65
    vis = np.empty((h, 0))
    # add the first column with the patch type names
    vis_tmp = np.empty((0,55))
    for t in tp:
        tp_patch = 255*np.ones((65,55))
        cv2.putText(tp_patch,t,(5,25),cv2.FONT_HERSHEY_DUPLEX , 1,0,1)
        vis_tmp = np.vstack((vis_tmp,tp_patch))
    vis = np.hstack((vis,vis_tmp))
    # add the actual patches
    for idx in ids:
        vis_tmp = np.empty((0,65))
        for t in tp:
            vis_tmp = np.vstack((vis_tmp,get_patch(seq,t,idx)))
        vis = np.hstack((vis,vis_tmp))
    return vis


# select a subset of types of patches to visualise
# tp = ['ref','e5','h5','t5']
#or visualise all - tps holds all possible types
tp = tps

# list of patch indices to visualise
ids = range(1,55)

# load a sample sequence
seq = hpatch_sequence(os.path.join(datadir, "hpatches-release", "v_calder"))
vis = vis_patches(seq,tp,ids)

# show
cv2.imshow("HPatches example", vis/255)
cv2.waitKey(0)

# or save
cv2.imwrite("patches.png", vis)

opencv-python图像预处理记录

 

2.

import os
import shutil
import numpy as np
import pcl
import cv2

def searchDirFile(rootDir, list_, path_):
    for dir_or_file in os.listdir(rootDir):
        filePath = os.path.join(rootDir, dir_or_file)
        if os.path.isfile(filePath):
            if os.path.basename(filePath).endswith('_DepthMap.tif'):
                temp = filePath.split('/')[-2]
                list_.append(temp)
                path_.append(filePath)
                #print(temp)
            else:
                continue
        elif os.path.isdir(filePath):
            searchDirFile(filePath, list_, path_)
        else:
            print('not file and dir '+os.path.basename(filePath))

path = "/home/dataset/"
namelist = []
pathlist = []
searchDirFile(path, namelist, pathlist)

or

import os
import cv2
import numpy as np

def searchDirFile(rootDir, list_, path_, endswith_):
    for dir_or_file in os.listdir(rootDir):
        filePath = os.path.join(rootDir, dir_or_file)
        if os.path.isfile(filePath):
            if os.path.basename(filePath).endswith(endswith_):
                temp = filePath.split('/')[-2]
                list_.append(temp)
                path_.append(filePath)
            else:
                continue
        elif os.path.isdir(filePath):
            searchDirFile(filePath, list_, path_, endswith_)
        else:
            print('not file and dir '+os.path.basename(filePath))

path = "/home/dataset"
namelist = []
pathlist = []
endswith = 'Texture_8Bit.png'
searchDirFile(path, namelist, pathlist, endswith)

 

3

# -- coding: utf-8 --
import os
import sys
import shutil
import numpy as np
from pathlib2 import Path

if __name__ == '__main__':

    lines = '**********'

    out_dir = './select_data'
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)

    # 数据地址
    before_dir = os.path.abspath(os.path.join(os.getcwd(), ".."))

    save_index = 200
    num = 0
    for dir_or_file in os.listdir(before_dir):
        num += 1
        print(num, "/", len(os.listdir(before_dir)))

        filePath = os.path.join(before_dir, dir_or_file)
        # 判断是否为文件
        if os.path.isfile(filePath):
            continue
        # 判断是否为目录
        elif os.path.isdir(filePath):
            sub_filePath1 = os.path.join(filePath, "Disk1")
            sub_filePath2 = os.path.join(filePath, "Disk2")
            if Path(sub_filePath1).exists() and Path(sub_filePath2).exists():
                for device_id_path in [sub_filePath1, sub_filePath2]:
                    for file in os.listdir(device_id_path):
                        m_id = file.split('-')
                        sub_id = "{}-{}-{}-{}".format(m_id[1],m_id[2],m_id[3],m_id[4])
                        id =  "{}-{}-{}-{}-{}".format(m_id[0],m_id[1],m_id[2],m_id[3],m_id[4])
                        if sub_id == lines:
                            subsubFilePath = os.path.join(device_id_path, file)

                            currentPng = os.path.join(subsubFilePath, 'OtherSampleFrame_IMG_Texture_8Bit.png')
                            currentTif = os.path.join(subsubFilePath, 'OtherSampleFrame_IMG_DepthMap.tif')
                            if Path(currentPng).exists() and Path(currentTif).exists():

                                shutil.copy(currentPng, os.path.join(out_dir, id+"_{:0>5d}_".format(save_index)+"OtherSampleFrame_IMG_Texture_8Bit.png"))
                                save_index += 1
                                #print(save_index)

4

python float 精度问题 和opencv-cpp有出入

# python的round函数将0.5向上入,OpenCV的cvRound函数将0.5向下舍
def cvRound(value):
    fractpart, intpart = math.modf(value)
    flag1 = (math.fabs(fractpart) < 0.50)
    if flag1:
        return int(intpart)
    else:
        return int(value + (0.5 if value >= 0 else -0.5))

def cut(num, c):
    str_num = str(num)
    return float(str_num[:str_num.index('.') + 1 + c])

 

相关标签: Python