(转)python图像操作

2023-05-16

转自:zbxzc
侵删

使用PIL完成

[python] view plain copy
import Image  
#打开图像  
img=Image.open('per00001.jpg')  
#显示  
img.show()  
#灰度化  
greyimg=img.convert('L')  
greyimg.show()  

import numpy as np  

#得到图像矩阵  
gimg_ndarr=np.asarray(greyimg,dtype='float64')/256  
#也可以这样  
#gimg_ndarr=np.array(greyimg,dtype='float64')  
print np.shape(gimg_ndarr)  

#下面对矩阵做一些变换  
gimg_ndarr=gimg_ndarr-0.5  

print gimg_ndarr  
gimg_ndarr=gimg_ndarr+0.5  
gimg_ndarr=gimg_ndarr*255  
print gimg_ndarr  

print gimg_ndarr.dtype  

#将gimg_ndarr数据类型由float64转化为int8,否则无法显示  
gimg_ndarr.astype(np.uint8)  

import pylab  

pylab.show(gimg_ndarr)  
#若以上操作都没问题,由gimg_ndarr将显示原图  
pylab.show()  


如下代码实现对文件夹里图像文件的遍历,然后随机截取一些图片,然后存入另一个文件夹里

crop() : 从图像中提取出某个矩形大小的图像。它接收一个四元素的元组作为参数,各元素为(left, upper, right, lower),坐标系统的原点(0, 0)是左上角。

[python] view plain copy
#coding:utf-8  
from PIL import Image  
import os  
import random  


root='/home/geo_linux/dataset/no_bike_no_person'  
def func(args,dire,fis): #回调函数的定义      
    for f in fis:      
        args[0].append(os.path.join(root, f))      
filelist=[]  
os.path.walk(root,func,(filelist,)) #遍历  

cropnum=10  

save_path='/home/geo_linux/dataset/neg_samples'  
for i in range(len(filelist)):  
    img=Image.open(filelist[i])  
    for j in range(cropnum):  
        leftupx=random.randint(0,img.size[0]-64-1)  
        leftupy= random.randint(0,img.size[1]-128-1)  
        img1=img.crop((leftupx,leftupy,leftupx+64,leftupy+128))  
        img1.save(os.path.join(save_path,str(i*cropnum+j)+'.png'))  


下面的代码实现对文件夹里所有图像的模糊与左右镜像翻转操作,结果存为图片

[python] view plain copy
#coding:utf-8  
from PIL import Image  
import ImageFilter  
import os  
import random  


root='/home/geo_linux/dataset/MIT_persons_jpg'  
def func(args,dire,fis): #回调函数的定义      
    for f in fis:      
        args[0].append(os.path.join(root, f))      
filelist=[]  
os.path.walk(root,func,(filelist,)) #遍历  

cnt=0  

save_path='/home/geo_linux/dataset/pos_samples'  
for i in range(len(filelist)):  
    img=Image.open(filelist[i])  
    img1=img.filter(ImageFilter.BLUR)  
    img1.save(os.path.join(save_path,str(cnt)+'.png'))  
    cnt+=1  
    img2=img.transpose(Image.FLIP_LEFT_RIGHT)  
    img2.save(os.path.join(save_path,str(cnt)+'.png'))  
    cnt+=1  




下面的代码实现对目录下所有图像文件的处理,提取数据存入本地文件

[python] view plain copy
#coding:utf-8  
import os     
import random  
import Image  
import numpy as np  
root='/home/geo_linux/dataset/pos_samples'  
pos_sample_list=[]    
def func(args,dire,fis): #回调函数的定义      
    for f in fis:      
        args[0].append(os.path.join(root, f))      
os.path.walk(root,func,(pos_sample_list,)) #遍历  

root='/home/geo_linux/dataset/neg_samples'  

neg_sample_list=[]  
os.path.walk(root,func,(neg_sample_list,)) #遍历  

train_pos_num=2200  
train_neg_num=2200  


def img2arr(imgname):  
   #图像转化为一维numpy数组  
   #imgname,string类型,文件绝对路径  
    img=Image.open(imgname)  
    grey=img.convert('L')  
    data=np.array(grey,dtype='uint8')  
    return data.flatten()  
#生成训练数据  
cnt1=0  
cnt2=0  
train_data=img2arr(pos_sample_list[0])  
del pos_sample_list[0]  
cnt1=1  
train_label=np.array(1,dtype='uint8')  

for i in range(train_pos_num+train_neg_num-1):  
      if cnt1<train_pos_num and cnt2<train_pos_num:  
         rng=random.randint(0,100)  
         if rng%2==0:  
            index=random.randint(0,len(pos_sample_list)-1)  
            train_data=np.hstack((train_data,img2arr(pos_sample_list[index])))  
            train_label=np.hstack((train_label,np.array(1,dtype='uint8')))  
            del pos_sample_list[index]  
            cnt1+=1  
         else:  
            index=random.randint(0,len(neg_sample_list)-1)  
            train_data=np.hstack((train_data,img2arr(neg_sample_list[index])))  
            train_label=np.hstack((train_label,np.array(0,dtype='uint8')))  
            del neg_sample_list[index]  
            cnt2+=1  
      elif cnt1<train_pos_num:  
            index=random.randint(0,len(pos_sample_list)-1)  
            train_data=np.hstack((train_data,img2arr(pos_sample_list[index])))  
            train_label=np.hstack((train_label,np.array(1,dtype='uint8')))  
            del pos_sample_list[index]  
            cnt1+=1  
      else:  
            index=random.randint(0,len(neg_sample_list)-1)  
            train_data=np.hstack((train_data,img2arr(neg_sample_list[index])))  
            train_label=np.hstack((train_label,np.array(0,dtype='uint8')))  
            del neg_sample_list[index]  
            cnt2+=1  

#生成测试数据  
test_data=img2arr(pos_sample_list[0])  
del pos_sample_list[0]  
test_label=np.array(1,dtype='uint8')  
for i in range(len(pos_sample_list)):  
     test_data=np.hstack((test_data,img2arr(pos_sample_list[i])))  
     test_label=np.hstack((test_label,np.array(1,dtype='uint8')))  
for i in range(len(neg_sample_list)):  
     test_data=np.hstack((test_data,img2arr(neg_sample_list[i])))  
     test_label=np.hstack((test_label,np.array(0,dtype='uint8')))  
#以二进制写入本地文件  
train_data.tofile('train_data.bin')  
train_label.tofile('train_label.bin')  
test_data.tofile('test_data.bin')  
test_label.tofile('test_label.bin')  



然后来看看我们存到本地的文件是不是预想的那样


[python] view plain copy
import numpy as np  
from PIL import Image  
data=np.fromfile('train_data.bin',dtype='uint8')  
data.shape=4400,128,64  
img=Image.frombuffer('L',(64,128),data[0],'raw','L',0,1)  
img.show()  

OK,成功显示图像

获取图片某一像素点的 (R,G,B)值

[python] view plain copy
from PIL import Image    

imagepath='/media/dell/Projects/test/US08621824-20140107-M00004-1-1.jpg'    
img = Image.open(imagepath)    
if img.mode not in ('L', 'RGB'):    
    img = img.convert('RGB')    
r, g, b = img.getpixel((10, 10))    





PIL中的Image和numpy中的数组array相互转换
1. PIL image转换成array


     img = np.asarray(image)
需要注意的是,如果出现read-only错误,并不是转换的错误,一般是你读取的图片的时候,默认选择的是"r","rb"模式有关。


修正的办法: 手动修改图片的读取状态


  img.flags.writeable = True  # 将数组改为读写模式


或者

    im = Image.open("lena.jpg")


    # 显示图片
    im.show() 

    im = im.convert("L") 
    data = im.getdata()
    data = np.matrix(data)
或者

  im = np.array(pil_im)


2. array转换成image

方法1

from PIL import Image
Image.fromarray(np.uint8(img))
注意img如果是uint16的矩阵而不转为uint8的话,Image.fromarray这句会报错

File "/usr/local/lib/python2.7/site-packages/PIL/Image.py", line 1884, in fromarray
    raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type
类似这个问题

PIL weird error after resizing image in skimage

方法2

import cv2

cv2.imwrite("output.png", out)

out可以是uint16类型数据



16位深度图像转8位灰度

matlab

img=imread('output.png')
img1=im2uint8(img)
imwrite(img1,'result.jpg')
或者Python

from PIL import Image
import numpy as np
import math
img=Image.fromarray(np.uint8(img_array/float(math.pow(2,16)-1)*255))
img.save('22.png')

Image.resize()
im.resize(size, filter) ⇒ image


Returns a resized copy of an image. The size argument gives the requested size in pixels, as a 2-tuple: (width, height).


The filter argument can be one of NEAREST (use nearest neighbour), BILINEAR (linear interpolation in a 2x2 environment), BICUBIC (cubic spline interpolation in a 4x4 environment), or ANTIALIAS (a high-quality downsampling filter). If omitted, or if the image has mode “1or “P”, it is set to NEAREST.


Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for large downsampling ratios (e.g. when creating thumbnails). You should use ANTIALIAS unless speed is much more important than quality.

Python图片转换成矩阵,矩阵数据转换成图片
Python实现图片与数组的转化


通道转换

注意Linux的convert命令会使得三通道的灰度图像变为单通道

Python图像处理库PIL中图像格式转换(二)


python的PIL图像处理


Image.copy()

Image.paste()

Python图像处理库PIL的ImageDraw模块介绍
http://blog.csdn.NET/icamera0/article/category/6069814
PIL doc


Polyline和Polygon的区别是什么
1)polygon 元素在连线的时候,会把所有的点连接起来,包括第一个点和最后一个点。
2)polyline 元素是不连接最后一个点和第一个点的。
这是polygon和polyline常见的区别

python,使用PIL库对图片进行操作

python计算机视觉编程
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

(转)python图像操作 的相关文章

  • Android 9.0 SecureElementService 初始化流程分析

    1 相关名词解释 NFC Near Field Communication xff0c 近场通信 xff0c 一种基于13 56 MHz 的短距离通信技术 NFCC NFC Controller xff0c NFC 控制器 xff0c 负责
  • 【Linux】生产者消费者模型 - 详解

    目录 一 生产者消费者模型概念 1 为何要使用生产者消费者模型 2 生产者消费者之间的关系 3 生产者消费者模型的优点 二 基于阻塞队列的生产消费模型 1 在阻塞队列中的三种关系 2 BlockingQueue hpp 阻塞队列类 3 Lo
  • word 批量设置图片大小

    word批量修改图片大小 固定长宽篇 方法一 xff1a 这部分要说的是把word中的所有图片修改成固定的并且相同的长和宽 xff01 1 打开word xff0c 工具 xff0d 宏 xff0d 宏 xff08 或者直接按Alt 43
  • 深度学习之 人脸识别(1) 人脸预处理

    人脸识别分两个部分 xff1a 第一步 xff1a 人脸图片预处理 xff0c 即检测图片中人脸并裁剪成指定尺寸的人脸图 第二步 xff1a 人脸识别 xff0c 包括模型训练 目标人脸分类训练 预测目标人脸 1 人脸检测原理 人脸识别 x
  • 制作自己的个人网站方法

    随着个人创业的流行 xff0c 很多个人也需要一个比较详细的网站来展示自己 xff0c 开展个人业务 xff0c 或者积累粉丝等等 那么怎么制作自己的个人网站呢 xff1f 又该怎么制作得更个性好看 xff1f 下面就跟大家分享下制作方法
  • 傻瓜书,VMware里的Ubuntu

    转自 xff1a http bbs cnw com cn thread 136057 1 1 html 傻瓜书 xff0c VMware里的Ubuntu 0 预备知识 什么是Ubuntu 如果不了解这一点 xff0c 本文的内容似乎与您无关
  • 痞子衡单片机排行榜(2022Q4)

    痞子衡单片机排行榜 2022Q4 继2020年开办的 痞子衡嵌入式半月刊 之后 xff0c 从2023年1月份开始痞子衡将为大家带来新项目 痞子衡单片机排行榜 一年分四季 xff0c 每个季度发布一期 xff0c 以MCU主频和Corema
  • [pdf]使用spire读取PDF的文字和图片

    概述 最近在梳理某项目的数据标准 xff0c 从标准网下载了很多PDF格式的标准文件 xff0c 需要提取文字和图片 xff0c 所以写了个程序提取 xff1b 本文使用了免费版的Spire 约束 免费版的Spire一次只能提取PDF的10
  • JetPack系列之ViewBinding

    viewBinding的作用启用视图绑定Activity中使用视图绑定Framgent中使用视图绑定与findViewById相比 viewBinding的作用 启用视图绑定之后 xff0c 系统会为每个xml生成一个绑定类 xff0c 我
  • 正则表达式记录

    去掉所有非1到9或者字母的其它字符 private static String dealWithVersion String versionArg String regex 61 34 1 9a zA Z 34 versionArg 61
  • 批量kill掉带有某些标识的进程的shell命令

    微信公众号 xff1a WELTest 分享一个常用命令 xff0c 批量杀掉一批进程 xff0c 这里以tomcat为例 xff1a ps ef grep tomcat awk 39 print 2 39 xargs kill 9 命令解
  • 【VUE】renren-fast-vue跳过验证码及使用mock数据单独添加一个页面

    效果图 解决办法 1 使用官方演示系统数据 1 把代理打开设置为True 2 在修改config目录下的index js的target值为 xff1a http demo open renren io renren fast server
  • 【软件测试】以闭环思维解决BUG复现率高问题

    bug复现率 要求复现BUG数 总bug数 背景 软件测试中提Bug 作为每个测试人员都应该遇到过 那每个测试人员可能也会遇到不停帮开发复现Bug的问题 如果Bug复现对环境要求不高 那复现成本还是比较低的 那如果环境复杂 那复现成本还是比
  • 自动化测试:功能移植之存储过程数据正确性验证

    自动化测试 功能移植之存储过程数据正确性验证 背景说明 系统架构的变更及调整 会引相同功能在不同架构上的移植工作 功能移植工作会产生多种变式 每种变式的测试策略是不一致的 本文主要讨论的变式为 业务不发生变动 只进行代码移植 结果表结构与原
  • docker mysql:5.6镜像安装mysqlreport、pt-query-digest

    更新debian源 echo 34 deb http ftp cn debian org debian stretch main 34 gt etc apt sources list echo 34 deb http ftp cn debi
  • 性能测试:模型趋势预测,让生产性能预测

    随着系统复杂度的提升 系统架构复杂度 部署规模也在逐步提升 这对性能测试测试 分析都带来挑战 古语有云 兵马未动粮草先行 针对测试而言测试环境及数据就是 粮草 性能测试如果环境 数据差异较大 性能测试出来的结果对生产指导意义就不是很大 那如
  • 【python黑帽子2】netcat.py编写及使用说明

    环境信息 python3 9 12 IDE为 xff1a vscode 源码 书中源码注意点 xff1a send函数中的if recv len lt 4096需要调整为if recv len lt 2 xff1a 该出的recv len值
  • 【Python黑帽子】proxy.py脚本

    span class token comment coding 61 utf 8 span span class token keyword import span sys span class token keyword import s
  • 【Jmeter】跨线程组共享数据

    背景 在性能测试中 xff0c 经常会遇见使用多线程组的情况 xff0c 例如用户登陆成功后 xff0c 对某个查询接口使用500个线程来进行压测 xff0c 这个时候就需要使用多线程组 设计说明 首先 xff0c 需要使用setUp Th
  • 【playwright】使用pytest-playwright执行用例时频繁打开浏览器

    背景说明 安装pytest playwright之后 xff0c 执行多个用例频繁打开浏览器 xff0c 而且无法给对应的fixture的scope设置为session 原因说明 pytest playwright定义了fixture的sc

随机推荐

  • (转)注册JNI函数的两种方式

    原文地址 http blog csdn net wwj 748 article details 52347341 前言 前面介绍过如何实现在Android Studio中制作我们自己的so库 xff0c 相信大家看过之后基本清楚如何在And
  • 【playwright】使用playwright实现拖动功能

    思路说明 使用locator定位到要拖动滑块元素 xff0c 如元素名叫ele 获取元素ele的bounding box含4分属性值 xff1a x xff0c y xff0c width xff0c height 把鼠标移动到元素ele的
  • 【playwright】pytest-playwright与allure结合,生成报告带有图片和录屏

    依赖的环境 需要安装allure命令行工具以及allure pytest插件 pytest playwright需要升级0 3 0版本 xff0c 改版本支持如下参数 xff1a Playwright browser 61 chromium
  • 【性能测试】缓慢的磁盘问题分析套路

    该文基于 性能之巅 xff1a 洞悉系统 企业与云计算 的1 9 1 缓慢的磁盘章节调整而来 用户问题 Scott 是一家中型公司里的系统管理员 数据库团队报告了一个支持ticket xff08 工单 xff09 xff0c 抱怨他们有一台
  • 【虚拟机】win 10的virtual box打开虚拟机报VERR_MEM_INIT_FAILED

    错误信息 解决办法 进入到 控制面板 程序 程序和功能 xff1a 选择 启用或关闭 Windows 功能 xff1a 重启电脑 xff0c 重新打开virtual下的虚拟机 xff0c 能够正常启动 xff1a
  • 【playwright】pytest-playwright增加代理服务选项

    playwright的代理设置参数为 xff1a https playwright dev python docs network http proxy 对pytest playwright py进行如下调整 xff0c 在browser
  • 【镜像源】分享三个镜像链接

    兰州大学 xff1a https mirror lzu edu cn 南京大学 xff1a https mirror nju edu cn docker官方镜像库 xff1a https github com docker library
  • 【Docker】基于系统iso构建docker基础镜像

    1 搭建本地yum源 1 xff09 将镜像通过光盘或U盘挂载到 mnt目录下 mount media kylin xxx iso mnt kylin 2 xff09 修改 etc yum repo d kylin x86 64 local
  • 【数据库】Oracle 12透明网关查询postgresql表某些字段不展示问题处理

    前置条件 1 对应版本列表 服务 版本 Oracle 12C 12 2 0 1 0 Heterogeneous Agent 12 2 0 1 0 odbc 2 3 1 unixODBC 2 3 6 psqlodbc 9 2 24 查看命令
  • 【机器学习】lightGBM是什么?

    梯度提升法 Gradient Boosting Machine 简记 GBM 以非参数方法 不假设函数形式 估计基函数 并在 函数空间 使用 梯度下降 进行近似求解 非参数方法包括K近邻法 决策树 以及基于决策树的装袋法 随机森林与提升法等
  • 【HttpRunner】学习准备

    1 安装python 3 7及以上版本 xff1a 2 安装fastapi xff1a pip install fastapi all 3 把如下代码粘贴复制到main py文件中 xff1a span class token keywor
  • Android中锁定文件的方法

    androidSDK中并没有锁定文件相关的api 但是android是基于linux操作系统的 linux比较底层 灵活性也更大 为了实现锁定文件的效果 大概有以下几种办法 用chmod命令修改文件读写权限利用linux中的多线程独占锁 启
  • 远程控制Ubuntu

    远程控制Ubuntu 在Ubuntu上安装team viewer或者向日葵 xff0c 进行远程控制 xff0c 这里记录采用team viewer方式的配置过程 xff0c 向日葵等远程控制类似 安装Ubuntu 官方下载Ubuntu系统
  • 信号降噪方法

    傅里叶变换 只能获取一段信号总体上包含哪些频率的成分 xff0c 但是对各成分出现的时刻并无所知 对非平稳过程 xff0c 傅里叶变换有局限性 短时傅里叶变换 xff08 Short time Fourier Transform STFT
  • C++ 带通滤波

    Butterworth Filter Coefficients The following files are for a library of functions to calculate Butterworth filter coeff
  • python之collections

    collections是日常工作中的重点 高频模块 xff0c 包含了一些特殊的容器 xff0c 针对Python内置的容器 xff0c 例如list dict set和tuple xff0c 常用类型有 xff1a namedtuple
  • git 指定下载文件,目录

    1 创建路径 mkdir gitfile cd lt 路径 gt eg xff1a cd home gitfile 2 创建一个空的本地仓库 git init 3 连接远程仓库GitHub git remote add f origin l
  • Ubuntu v4l2 视屏流花屏问题

    之前用的好好解析YUV xff0c MJPEG 换了个核心板就不好使了 xff0c opencv3 4 6 gt gt gt opencv4 5 5 xff0c Mat xff0c cvMat xff0c IplImage 的类型转换也不好
  • qt qmake .qrc hasmodification time xxx in the future

    原因 xff1a 跨平台生成的 qrc 文件创建时间与目标平台时间不一致导致 xff0c 如win写的 copy 到 Linux xff0c 再编译可能会遇到该bug 导致无法qmake 与 build 解决 xff1a touch qrc
  • (转)python图像操作

    转自 xff1a zbxzc 侵删 使用PIL完成 python view plain copy span class hljs keyword import span Image span class hljs comment 打开图像