LoginSignup
2
8

More than 5 years have passed since last update.

Python文字列や画像を保存

Posted at

ブログに書くほどではないけど忘れたく無いノウハウを書き連ねていきます。

画像の読み書き with Opencv

Opencv3を用いた環境を仮定。

import cv2

# read Image with GrayScale
Img =  cv2.imread("Image.png",0)

# save Image
cv2.imwrite("Image.jpg",Img)

名前が先なのが結構ややこい。

表示は次の2パターン。
matplotlibはグレー指定を忘れて変な色で表示されがち。

# Using OpenCV
cv2.imshow("Read Image",Img)
cv2.waitKey(0)

# Using Matplotlib
import matplotlib.pyplot as plt # matplotlibの描画系
plt.imshow(Iref,cmap='gray')

numpy行列をtxtやcsvに吐き出し

Txtで吐き出し

numpyにはsavetxtというのがあるらしい。
http://conta.hatenablog.com/entry/2013/12/02/183538
ここにReferenceを書いてくれている人がいるので詳細はこちらで。
https://deepage.net/features/numpy-loadsavetxt.html

import numpy as np

# for 何らかのループでデータをappend
# dataset.append(何某か)

# 整形
dataset = np.array(dataset,np.float32).reshape(H,W)
# 出力
np.savetxt('out.txt',dataset,delimiter=',')

CSV吐き出し

さっきのsavetxtで同様にcsvとしても保存可能。

import numpy as np

#csvファイルとして保存
np.savetxt('out.csv',dataset,delimiter=',')

超余談:Dialogを呼んでファイルを選択,ファイル名を取得

一番面倒なのがファイル名を取得する場所。

非常に便利そうなものをここの記事からお借りした。

自分の目的用に書き直すとこうなる。画像ファイルのみを選択してその名前を返す関数である。

# Import module
import os, tkinter, tkinter.filedialog, tkinter.messagebox

def GetFileName():
    # Show Dialog
    root = tkinter.Tk()
    root.withdraw()
    # Any file type of Image
    fTyp = [("",["*.png","*.jpg","*.bmp"])]
    iDir = os.path.abspath(os.path.dirname(__file__))
    tkinter.messagebox.showinfo('Image choice','Choose Base Image!')
    file = tkinter.filedialog.askopenfilename(filetypes = fTyp,initialdir = iDir)
    return file

2
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
8