본문 바로가기
언어 정리/python_lib,일급함수

PIL , 출력문 저장 lib(write,print,sys.out)

by 알 수 없는 사용자 2022. 8. 4.

참조

개념이나 모드 설명

https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes

 

Concepts

The Python Imaging Library handles raster images; that is, rectangles of pixel data. Bands: An image can consist of one or more bands of data. The Python Imaging Library allows you to store several...

pillow.readthedocs.io

 

사용법 예시 

https://pillow.readthedocs.io/en/stable/reference/Image.html

 

Image Module

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, a...

pillow.readthedocs.io


다운 :

pip install pillow

코드 정리 (( 아직 미완 ))

#-----------------#-----------------#-----------------#-----------------
# PIL from 정리
PIL.Image.fromarray(obj, mode=None)
PIL.Image.frombytes(mode, size, data, decoder_name='raw', *args)
PIL.Image.frombuffer(mode, size, data, decoder_name='raw', *args)







#-----------------#-----------------#-----------------#-----------------
# png 파일을 byte 파일로 변환
from PIL import Image
import numpy as np
import io

f = open('q.png','rb')
a= f.read()
with open('q_png.txt','w') as file:
        file.write(a)
print(a)
print(type(a))

"""
�Ej7g�-]<��zy����KчF�����ur�%IEND�B`�
<type 'str'>
"""

#-----------------#-----------------#-----------------#-----------------
# png 파일을 np.array 파일로 변환
from PIL import Image
import numpy as np
im = Image.open("q.png")
a = np.asarray(im)

print(a)
print(type(a))

"""
[[[179 188 187]
  [180 189 188]
  [179 186 186]
  ...
  ...
  [204 216 209]
  [205 217 212]
  [204 216 211]]]
<type 'numpy.ndarray'>
"""

#-----------------#-----------------#-----------------#-----------------
# np.array 파일을 png 파일로 변환
from PIL import Image
import numpy as np
tmp = Image.open("q.png")
a = np.asarray(tmp)
#print(a)
#print(type(a))

#a = np.full((1, 1), 300)
print(type(a))
im = Image.fromarray(a, mode="RGB")
im.getpixel((0, 0))  # (44, 1, 0)
im.save('arr_q.png')
print(type(im))

"""
<type 'numpy.ndarray'>
<class 'PIL.Image.Image'>
"""

#-----------------#-----------------#-----------------#-----------------
# camera data 받고 저장
import rospy
from sensor_msgs.msg import CompressedImage
import sys


def save_data(_path,_data):
        temp = sys.stdout
        with open(_path, "w") as sys.stdout:
                print(type(_data))
                sys.stdout = temp

def callback(msg):
        # print("11111111111111111111 {} ".format(type(msg.data)))
        # print("222222222222222 {} ".format(type(msg)))
        print('{}'.format(type(msg)))
        save_data('./ros_data/img_1',msg)
        print('end')

        rospy.sleep(100000)

rospy.init_node('camera_sub')

sub = rospy.Subscriber('/cv_camera/camera_head/image_raw/compressed', CompressedImage, callback)
rospy.spin()

#-----------------#-----------------#-----------------#-----------------
# camera data 한장만 받고 저장 후 , np.array로 변환후 jpg파일로 변환
import rospy
from sensor_msgs.msg import CompressedImage
import sys

class SaveByteData(object):
        def __init__(self, _node_name, _topic_name, _data_type, callback_func):
                self._node_name = _node_name
                self._topic_name = _topic_name
                self._data_type = _data_type
                self._callback_func = callback_func
                rospy.init_node(self._node_name)

        def save_data(self, _path, _data):
                temp = sys.stdout
                with open(_path, "w") as sys.stdout:
                        print(_data)
                        sys.stdout = temp

        def callback(self, msg):
                # print("11111111111111111111 {} ".format(type(msg.data)))
                # print("222222222222222 {} ".format(type(msg)))
                print('{}'.format(type(msg)))
                self.save_data('./ros_data/img_1', msg)
                print('end')
                rospy.sleep(100000)

        def sub_data(self):
                rospy.Subscriber(self._topic_name, self._data_type, self.callback)

if __name__ == '__main__':
        NODE_NAME = 'camera_sub'
        TOPIC_NAME = '/cv_camera/camera_head/image_raw/compressed'
        DATA_TYPE = CompressedImage
        callback_func = 1

        save_byte_data_obj = SaveByteData(NODE_NAME,TOPIC_NAME,DATA_TYPE,callback_func)
        save_byte_data_obj.sub_data()
        rospy.spin()


#-----------------#-----------------#-----------------#-----------------
# camera data 백업용(재택) , 여러장 받아서 따로따로 저장 해줌
import rospy
from sensor_msgs.msg import CompressedImage
import sys


class aa(object):
        def __init__(self):
                self.i = 1
                rospy.init_node('camera_sub')

        def save_data(self,_path,_data):
                temp = sys.stdout
                with open(_path, "w") as sys.stdout:
                        print(_data)
                        sys.stdout = temp

        def callback(self,msg):
                print('{}'.format(type(msg)))
                name = ('./ros_data/img_{}'.format(self.i))
                print(name)
                self.save_data(name,msg)
                #print('end')
                self.i=self.i+1
                #rospy.sleep(100000)

        def on(self):
                sub = rospy.Subscriber('/cv_camera/camera_head/image_raw/compressed', CompressedImage, self.callback)
                rospy.spin()

a = aa()
a.on()

#-----------------#-----------------#-----------------#-----------------

 

 

 

 

 

 

 

 

 

 

 

 

 

 


출력문 저장 lib 

1. write()함수를 사용하여 Python에서 파일로 출력 인쇄
2. print()함수를 사용하여 Python에서 파일로 출력 인쇄
3. sys.stdout을 사용하여 Python에서 파일로 출력 인쇄
4. contextlib.redirect_stdout()함수를 사용하여 Python에서 파일로 출력 인쇄

---

여기서 중요한점은 1번은 str타입만 저장이 가능함

예를들어 3번은 클래스타입을 print한 걸 그대로 저장하지만 , 1번에 클래스타입을 write한다고 하면 에러난다.

---

 

1. 

a = '12345'
with open('./output.txt', 'w') as f:
        f.write(a)

2.

 

with open("randomfile.txt", "w") as external_file:
    add_text = "This text will be added to the file"
    print(add_text, file=external_file)
    external_file.close()

3.

import sys
 
file_path = 'randomfile.txt'
sys.stdout = open(file_path, "w")
print("This text will be added to the file")

 

4.

import contextlib
 
file_path = 'randomfile.txt'
with open(file_path, "w") as o:
    with contextlib.redirect_stdout(o):
        print("This text will be added to the file")

 

댓글