【Python】采用opencv库的cv2.imread()方法读图片及其他尝试(os.listdir()、cvc2.rezise() )

一、关键知识点介绍:

1、学习过程部分博客记录
这里参考了许多博客,随便贴几个好了
opencv-python 学习笔记1:简单的图片处理

python数字图像处理(2):图像的读取、显示与保存

python读取图像的几种方法

2、opencv读图片尝试代码及结果

def test_lm():
    file_path='./ORL/s1/'
    #cv2.IMREAD_COLOR:读入一副彩色图片; //可用1代替 
    #cv2.IMREAD_GRAYSCALE:以灰度模式读入图片; //可用0代替
    #img=cv2.imread(file_path+'lm.jpg',cv2.IMREAD_GRAYSCALE)
    img=cv2.imread(file_path+'lm.jpg',1)
    #缩小,interpolation为插值方法
    img= cv2.resize(img,(200,200),interpolation = cv2.INTER_AREA)
    cv2.imshow('image',img)#建立image窗口显示图片
    #保存图片,可设置保存路径,这里为当前路径
    cv2.imwrite('test.png',img)

在这里插入图片描述 在这里插入图片描述
cv2.IMREAD_COLOR:读入一副彩色图片; //可用1代替

cv2.IMREAD_GRAYSCALE:以灰度模式读入图片; //可用0代替

cv2.IMREAD_UNCHANGED:读入一幅图片,并包括其alpha通道

3、Python os.listdir() 方法
os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。这个列表以字母顺序

def test_os():
    path = "./ORL/s1/"
    dirs = os.listdir( path )   
    # 输出所有文件和文件夹
    for file in dirs:
       print(file)

在这里插入图片描述 在这里插入图片描述

4、cvc2.rezise() 修改图片大小函数
Opencv库中的cv2.resize()函数主要功能是实现图片放缩,这里最值得一提的是它放缩的时候插值的参数是可以选择的:
ⅠINTER_NEAREST - 最近邻插值法
ⅡINTER_LINEAR - 双线性插值法(默认)
ⅢINTER_AREA - 基于局部像素的重采样(resampling using pixel area relation)。对于图像抽取(image decimation)来说,这可能是一个更好的方法。但如果是放大图像时,它和最近邻法的效果类似。
ⅣINTER_CUBIC - 基于4x4像素邻域的3次插值法
ⅤINTER_LANCZOS4 - 基于8x8像素邻域的Lanczos插值

时间有限,不求甚解ㄟ( ▔, ▔ )ㄏ

二、练习过程其他代码

直接上练习过程中的完整代码
(主要演示了读取两层文件夹中的图片的学习尝试过程)

import os
import cv2                #导入opencv库
import numpy as np 
import pandas as pd

def test0(file_path): 
    #创建一个空矩阵
    train_set = np.zeros(shape=[1,30*30])
    
    for filename in os.listdir(file_path):              #listdir的参数是文件夹的路径
        img = cv2.imread(file_path+'/'+filename,cv2.IMREAD_GRAYSCALE)   #读取图片,第二个参数表示以灰度图像读入
        cv2.imshow("test_imread",img)#
        #对图片进行缩放,第一个参数是读入的图片,第二个是制定的缩放大小,第三个参数为插值的选择
        #cv2.INTER_AREA基于局部像素的重采样,网上说这是一个很好的方法
        #img= cv2.resize(img,(30,30),interpolation = cv2.INTER_AREA)
        #cv2.INTER_NEAREST 最近邻插值法
        #img= cv2.resize(img,(60,60),interpolation = cv2.INTER_NEAREST)
        #cv2.INTER_CUBIC 基于4x4像素邻域的3次插值法
        img= cv2.resize(img,(30,30),interpolation = cv2.INTER_CUBIC)
        #cv2.INTER_LANCZOS4 基于8x8像素邻域的Lanczos插值
        #img= cv2.resize(img,(30,30),interpolation = cv2.INTER_LANCZOS4)

        cv2.imshow("test_imread",img)
        res=img
        sp = img.shape
        print(sp)
        res_1 = res.reshape(1,sp[0]*sp[1])       #将表示图片的二维矩阵转换成一维
        res_2= res_1.tolist()     #将numpy.narray类型的矩阵转换成list
        #train_set.append(res_2)   #将list添加到已有的list中
        train_set=np.row_stack((train_set,res_2))
        #print(train_set)'''
    return train_set


def test1():
    file_path='./ORL/s1'
    for filename in os.listdir(file_path):              #listdir的参数是文件夹的路径
        print (filename)                                 #此时的filename是文件夹中文件的名称
        img = cv2.imread(file_path+'/'+filename,cv2.IMREAD_GRAYSCALE)   #读取图片,第二个参数表示以灰度图像读入
        img= cv2.resize(img,(618,700))              #对图片进行缩放,第一个参数是读入的图片,第二个是制定的缩放大小
        cv2.imshow("test_imread",img)

def test2():
    file_path='./ORL/s1'
    for i in range(1,11):              #listdir的参数是文件夹的路径                               #此时的filename是文件夹中文件的名称
        img = cv2.imread(file_path+'/'+str(i)+'.bmp',cv2.IMREAD_GRAYSCALE)   #读取图片,第二个参数表示以灰度图像读入
        #img= cv2.resize(img,(300,300))              #对图片进行缩放,第一个参数是读入的图片,第二个是制定的缩放大小
        print(type(img))
        cv2.imshow("test_imread",img)
        img=pd.DataFrame(img)
        print(type(img))

def test3():
    file_path='./ORL/s1/'
    train_set = np.zeros(shape=[1,112*92])
    print(type(train_set))
    train_set = pd.DataFrame(train_set)
    print(train_set.shape) 
    
    for i in range(1,11):              #listdir的参数是文件夹的路径                              
        img = cv2.imread(file_path+str(i)+'.bmp',cv2.IMREAD_GRAYSCALE)   #读取图片,第二个参数表示以灰度图像读入
        cv2.imshow("test_imread",img)
        img=img.reshape(1,img.shape[0]*img.shape[1])
        print(img.shape)
        img=pd.DataFrame(img)
        train_set=pd.concat([train_set,img],axis=0)
    ls=list(range(0,train_set.shape[0]))
    train_set.index=ls
    train_set.drop(labels=0,axis=0,inplace=True) #去掉第一行
    print(type(train_set))
    print(train_set)     

#两层循环有选择地读取
def test4():
    file_path='./ORL/'
    train_set = np.zeros(shape=[1,112*92])
    train_set = pd.DataFrame(train_set)
    target=[]
    for i in range(1,41):        
        for j in range(1,6):           #listdir的参数是文件夹的
            target.append(i)
            img = cv2.imread(file_path+'s'+str(i)+'/'+str(j)+'.bmp',cv2.IMREAD_GRAYSCALE)   #读取图片,第二个参数表示以灰度图像读入
            cv2.imshow("test_imread",img)
            img=img.reshape(1,img.shape[0]*img.shape[1])
            print(img.shape)
            img=pd.DataFrame(img)
            train_set=pd.concat([train_set,img],axis=0)
    train_set.index=list(range(0,train_set.shape[0])) #设置行索引
    train_set.drop(labels=0,axis=0,inplace=True) #去掉第一行
    target=pd.DataFrame(target)
    print(type(train_set))
    print(train_set)
    return train_set,target


#直接这么转pd.DataFrame(target)是错误的
def test5():
    file_path='./ORL/'
    train_set = np.zeros(shape=[1,112*92]) 
    pd.DataFrame(train_set)
    target=[]
    for i in range(1,41):        
        for j in range(1,6):           
            target.append(i)
            img = cv2.imread(file_path+'s'+str(i)+'/'+str(j)+'.bmp',cv2.IMREAD_GRAYSCALE)  
            cv2.imshow("test_imread",img)
            img=img.reshape(1,img.shape[0]*img.shape[1])
            pd.DataFrame(img)
            train_set=pd.concat([train_set,img],axis=0)
    train_set.index=list(range(0,train_set.shape[0])) 
    train_set.drop(labels=0,axis=0,inplace=True) 
    pd.DataFrame(target)
    
    return train_set,target

def test6():
    file_path='./ORL/'
    train_set = np.zeros(shape=[1,112*92])
    train_set = pd.DataFrame(train_set)
    target=[]
    for i in range(1,41):        
        for j in range(1,6):           #listdir的参数是文件夹的
            target.append(i)
            img = cv2.imread(file_path+'s'+str(i)+'/'+str(j)+'.bmp',cv2.IMREAD_GRAYSCALE)   #读取图片,第二个参数表示以灰度图像读入
            cv2.imshow("test_imread",img)
            img=img.reshape(1,img.shape[0]*img.shape[1])
            img=pd.DataFrame(img)
            train_set=pd.concat([train_set,img],axis=0)
    train_set.index=list(range(0,train_set.shape[0])) #设置行索引
    train_set.drop(labels=0,axis=0,inplace=True) #去掉第一行
    target=pd.DataFrame(target)
    return train_set,target

if __name__ == '__main__':
      data_train,target_train=test6()
      print("data_train:",data_train)
      print("target_train:",target_train)
      print(type(data_train))
      print(type(target_train))
      
      

    


  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值