Python模块_PyLibTiff读取tif文件的实例

Usage example (libtiff wrapper)

from libtiff import TIFF
# to open a tiff file for reading:
tif = TIFF.open('filename.tif', mode='r')
# to read an image in the currect TIFF directory and return it as numpy array:
image = tif.read_image()
# to read all images in a TIFF file:
for image in tif.iter_images(): # do stuff with image
# to open a tiff file for writing:
tif = TIFF.open('filename.tif', mode='w')
# to write a image to tiff file
tif.write_image(image)

Usage example (pure Python module)

from libtiff import TIFFfile, TIFFimage
# to open a tiff file for reading
tif = TIFFfile('filename.tif')
# to return memmaps of images and sample names (eg channel names, SamplesPerPixel>=1)
samples, sample_names = tiff.get_samples()
# to create a tiff structure from image data
tiff = TIFFimage(data, description='')
# to write tiff structure to file
tiff.write_file('filename.tif', compression='none') # or 'lzw'
del tiff # flushes data to disk
from libtiff import TIFF
from scipy import misc 

##tiff文件解析成图像序列
##tiff_image_name: tiff文件名;
##out_folder:保存图像序列的文件夹
##out_type:保存图像的类型,如.jpg、.png、.bmp等
def tiff_to_image_array(tiff_image_name, out_folder, out_type):  

  tif = TIFF.open(tiff_image_name, mode = "r")
  idx = 0
  for im in list(tif.iter_images()):
    #
    im_name = out_folder + str(idx) + out_type
    misc.imsave(im_name, im)
    print im_name, 'successfully saved!!!'
    idx = idx + 1
  return 

##图像序列保存成tiff文件
##image_dir:图像序列所在文件夹
##file_name:要保存的tiff文件名
##image_type:图像序列的类型
##image_num:要保存的图像数目
def image_array_to_tiff(image_dir, file_name, image_type, image_num): 

  out_tiff = TIFF.open(file_name, mode = 'w') 

  #这里假定图像名按序号排列
  for i in range(0, image_num):
    image_name = image_dir + str(i) + image_type
    image_array = Image.open(image_name)
    #缩放成统一尺寸
    img = image_array.resize((480, 480), Image.ANTIALIAS)
    out_tiff.write_image(img, compression = None, write_rgb = True) 

  out_tiff.close()
  return  

用opencv读取

import cv2

cv2.imread("filename",flags)
对于cv2,imread的关于通道数和位深的flags有四种选择:

IMREAD_UNCHANGED = -1#不进行转化,比如保存为了16位的图片,读取出来仍然为16位。
IMREAD_GRAYSCALE = 0#进行转化为灰度图,比如保存为了16位的图片,读取出来为8位,类型为CV_8UC1。
IMREAD_COLOR = 1#进行转化为RGB三通道图像,图像深度转为8位
IMREAD_ANYDEPTH = 2#保持图像深度不变,进行转化为灰度图。
IMREAD_ANYCOLOR = 4#若图像通道数小于等于3,则保持原通道数不变;若通道数大于3则只取取前三个通道。图像深度转为8位
对于多通道TIFF图像,若要保证图像数据的正常读取,显然要选择IMREAD_UNCHANGED作为imread的flags设置值。

安装pylibtiff

##PIL使用

导入 Image 模块。然后通过 Image 类中的 open 方法即可载入一个图像文件。如果载入文件失败,则会引起一个 IOError ;若无返回错误,则 open 函数返回一个 Image 对象。现在,我们可以通过一些对象属性来检查文件内容,即:

>>> import Image
>>> im = Image.open("j.jpg")
>>> print im.format, im.size, im.mode
JPEG (440, 330) RGB

Image 类的实例有 5 个属性,分别是:

format: 以 string 返回图片档案的格式(JPG, PNG, BMP, None, etc.);如果不是从打开文件得到的实例,则返回 None。

mode: 以 string 返回图片的模式(RGB, CMYK, etc.);完整的列表参见 官方说明·图片模式列表

size: 以二元 tuple 返回图片档案的尺寸 (width, height)

palette: 仅当 mode 为 P 时有效,返回 ImagePalette 示例

info: 以字典形式返回示例的信息

函数概貌。

Reading and Writing Images : open( infilename ) , save( outfilename ) Cutting and Pasting and Merging Images :

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

系统的原点(0, 0)是左上角。

paste() :

merge() :

>>> box = (100, 100, 200, 200)
 >>> region = im.crop(box)
 >>> region.show()
 >>> region = region.transpose(Image.ROTATE_180)
 >>> region.show()
 >>> im.paste(region, box)
 >>> im.show()

旋转一幅图片:

def roll(image, delta):
  "Roll an image sideways"

  xsize, ysize = image.size

  delta = delta % xsize
  if delta == 0: return image

  part1 = image.crop((0, 0, delta, ysize))
  part2 = image.crop((delta, 0, xsize, ysize))
  image.paste(part2, (0, 0, xsize-delta, ysize))
  image.paste(part1, (xsize-delta, 0, xsize, ysize))

  return image

几何变换

>>>out = im.resize((128, 128))           #
 >>>out = im.rotate(45)               #逆时针旋转 45 度角。
 >>>out = im.transpose(Image.FLIP_LEFT_RIGHT)    #左右对换。
 >>>out = im.transpose(Image.FLIP_TOP_BOTTOM)    #上下对换。
 >>>out = im.transpose(Image.ROTATE_90)       #旋转 90 度角。
 >>>out = im.transpose(Image.ROTATE_180)      #旋转 180 度角。
>>>out = im.transpose(Image.ROTATE_270)      #旋转 270 度角。

Image 类的 thumbnail() 方法可以用来制作缩略图。它接受一个二元数组作为缩略图的尺寸,然后将示例缩小到指定尺寸。

import os, sys
from PIL import Image

for infile in sys.argv[1:]:
  outfile = os.path.splitext(infile)[0] + ".thumbnail"
  if infile != outfile:
    try:
      im  = Image.open(infile)
      x, y = im.size
      im.thumbnail((x//2, y//2))
      im.save(outfile, "JPEG")
    except IOError:
      print "cannot create thumbnail for", infile

这里我们用 im.size 获取原图档的尺寸,然后以 thumbnail() 制作缩略图,大小则是原先图档的四分之一。同样,如果图档无法打开,则在终端上打印无法执行的提示。

PIL.Image.fromarray(obj, mode=None)

Creates an image memory from an object exporting the array interface (using the buffer protocol).

If obj is not contiguous, then the tobytes method is called and frombuffer() is used.

Parameters:
obj – Object with array interface
mode – Mode to use (will be determined from type if None) See: Modes.
Returns:
An image object.

New in version 1.1.6.

PIL文档

以上这篇Python模块_PyLibTiff读取tif文件的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 浅谈python下tiff图像的读取和保存方法

    对比测试 scipy.misc 和 PIL.Image 和 libtiff.TIFF 三个库 输入: 1. (读取矩阵) 读入uint8.uint16.float32的lena.tif 2. (生成矩阵) 使用numpy产生随机矩阵,float64的mat import numpy as np from scipy import misc from PIL import Image from libtiff import TIFF # # 读入已有图像,数据类型和原图像一致 tif32 = mi

  • Python 读取某个目录下所有的文件实例

    在处理数据的时候,因为没有及时的去重,所以需要重新对生成txt进行去重. 可是一个文件夹下有很多txt,总不可能一个一个去操作,这样效率太低了.这里我们需要用到 os 这个包 关键的代码 <span style="font-size:14px;"># coding=utf-8 #出现了中文乱码的问题,于是我无脑utf-8 .希望后期的学习可以能理解 import os import os.path import re import sys import codecs rel

  • Pytorch之保存读取模型实例

    pytorch保存数据 pytorch保存数据的格式为.t7文件或者.pth文件,t7文件是沿用torch7中读取模型权重的方式.而pth文件是python中存储文件的常用格式.而在keras中则是使用.h5文件. # 保存模型示例代码 print('===> Saving models...') state = { 'state': model.state_dict(), 'epoch': epoch # 将epoch一并保存 } if not os.path.isdir('checkpoin

  • Python模块的定义,模块的导入,__name__用法实例分析

    本文实例讲述了Python模块的定义,模块的导入,__name__用法.分享给大家供大家参考,具体如下: 相关内容: 什么是模块 模块的导入 模块的导入 自模块的导入 同级目录导入 不同级目录导入 目录内导入目录外 目录外导入目录内 __name__ 什么是模块: 在Python中,模块就是一个个方法和类的仓库,如果我们想要使用某个模块中的某个方法或类,那么我们就需要导入对应的模板. [python有内置方法.类,所以有些方法我们并不需要导入模块] 模块的使用:模块.函数 ,     模块.类

  • 使用Rasterio读取栅格数据的实例讲解

    Rasterio简介 有没有觉得用GDAL的Python绑定书写的代码很不Pythonic,强迫症的你可能有些忍受不了.不过,没关系,MapBox旗下的开源库Rasterio帮我们解决了这个痛点. Rasterio是基于GDAL库二次封装的更加符合Python风格的主要用于空间栅格数据处理的Python库. Rasterio中栅格数据模型基本和GDAL类似,需要注意的是: 在Rasterio 1.0以后,对于GeoTransform的表示弃用了GDAL风格的放射变换,而使用了Python放射变换

  • Python模块_PyLibTiff读取tif文件的实例

    Usage example (libtiff wrapper) from libtiff import TIFF # to open a tiff file for reading: tif = TIFF.open('filename.tif', mode='r') # to read an image in the currect TIFF directory and return it as numpy array: image = tif.read_image() # to read al

  • 简单了解Python读取大文件代码实例

    这篇文章主要介绍了简单了解Python读取大文件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 通常对于大文件读取及处理,不可能直接加载到内存中,因此进行分批次小量读取及处理 I.第一种读取方式 一行一行的读取,速度较慢 def read_line(path): with open(path, 'r', encoding='utf-8') as fout: line = fout.readline() while line: line

  • Python导入父文件夹中模块并读取当前文件夹内的资源

    在某些特殊情况下,我们的 Python 脚本需要调用父目录下的其他模块.例如: 在编写 GNE 的测试用例时,有一个脚本 generate_new_cases.py放在 tests文件夹中.而 tests 文件夹与 gne 文件夹放在同一个位置.其中 gne 文件夹是一个包.我现在需要从generate_new_cases.py 文件中导入 gne 里面的一个类GeneralNewsExtractor. 为了简化问题,我单独写了一个演示的样例.它的文件结构与每个文件中的内容如下: 现在,我直接在

  • Python解析并读取PDF文件内容的方法

    本文实例讲述了Python解析并读取PDF文件内容的方法.分享给大家供大家参考,具体如下: 一.问题描述 利用python,去读取pdf文本内容. 二.效果 三.运行环境 python2.7 四.需要安装的库 pip install pdfminer 五.实现源代码 代码1(win64) # coding=utf-8 import sys reload(sys) sys.setdefaultencoding('utf-8') import time time1=time.time() impor

  • python 批量解压压缩文件的实例代码

    下面给大家介绍python 批量解压压缩文件的实例代码,代码如下所述: #/usr/bin/python#coding=utf-8import os,sys import zipfile open_path='e:\\data'save_path='e:\\data' os.chdir(open_path) #转到路径 #首先,通过zipfile模块打开指定位置zip文件 #传入文件名列表,及列表文件所在路径,及存储路径def Decompression(files,file_path,save

  • Python使用pandas处理CSV文件的实例讲解

    Python中有许多方便的库可以用来进行数据处理,尤其是Numpy和Pandas,再搭配matplot画图专用模块,功能十分强大. CSV(Comma-Separated Values)格式的文件是指以纯文本形式存储的表格数据,这意味着不能简单的使用Excel表格工具进行处理,而且Excel表格处理的数据量十分有限,而使用Pandas来处理数据量巨大的CSV文件就容易的多了. 我用到的是自己用其他硬件工具抓取得数据,硬件环境是在Linux平台上搭建的,当时数据是在运行脚本后直接输出在termin

  • 五分钟学会Python 模块和包、文件

    目录 一. 模块 1.模块的概念 2.模块的两种导入方式 3.模块的搜索顺序[扩展] 4. name 属性 二.包 1.概念 三.发布模块(知道) 1. 制作发布压缩包步骤 2.安装模块 3.pip 安装第三方模块 四.文件 1.文件的基本操作 2.文件/目录的常用管理操作 3.Ptyhon 2.x 中如何使用中文 五.命名空间和作用域 1.dir()函数 2.globals()和locals()函数 3.reload()函数 一. 模块 1.模块的概念 模块是 Python 程序架构的一个核心

  • Python多进程分块读取超大文件的方法

    本文实例讲述了Python多进程分块读取超大文件的方法.分享给大家供大家参考,具体如下: 读取超大的文本文件,使用多进程分块读取,将每一块单独输出成文件 # -*- coding: GBK -*- import urlparse import datetime import os from multiprocessing import Process,Queue,Array,RLock """ 多进程分块读取文件 """ WORKERS = 4

  • python或C++读取指定文件夹下的所有图片

    本文实例为大家分享了python或C++读取指定文件夹下的所有图片,供大家参考,具体内容如下 1.python读取指定文件夹下的所有图片路径和图片文件名 import cv2 from os import walk,path def get_fileNames(rootdir): data=[] prefix = [] for root, dirs, files in walk(rootdir, topdown=True): for name in files: pre, ending = pa

  • 通过Pandas读取大文件的实例

    当数据文件过大时,由于计算机内存有限,需要对大文件进行分块读取: import pandas as pd f = open('E:/学习相关/Python/数据样例/用户侧数据/test数据.csv') reader = pd.read_csv(f, sep=',', iterator=True) loop = True chunkSize = 100000 chunks = [] while loop: try: chunk = reader.get_chunk(chunkSize) chun

随机推荐