加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

python PIL 图像处理模块以及array的互相转换,基本图像处理收集

(2016-03-02 16:28:14)
分类: python
http://pillow.readthedocs.org/en/3.1.x/reference/Image.html
https://github.com/yipinp/ADAS_Lab

PIL 库中比较好用的就是fromarray等。

PIL.Image.fromarray(objmode=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.



PIL.Image.frombytes(modesizedatadecoder_name='raw'*args)

Creates a copy of an image memory from pixel data in a buffer.

In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data).

You can also use any pixel decoder supported by PIL. For more information on available decoders, see the section Writing Your Own File Decoder.

Note that this function decodes pixel data only, not entire images. If you have an entire image in a string, wrap it in a BytesIO object, and use open() to load it.

Parameters:
  • mode – The image mode. See: Modes.
  • size – The image size.
  • data – A byte buffer containing raw data for the given mode.
  • decoder_name – What decoder to use.
  • args – Additional parameters for the given decoder.
Returns:

An Image object.

在python中本身还有bytearray

bytearray([source [, encoding [, errors]]])

中文说明:

bytearray([source [, encoding [, errors]]])返回一个byte数组。Bytearray类型是一个可变的序列,并且序列中的元素的取值范围为 [0 ,255]。


参数source:


如果source为整数,则返回一个长度为source的初始化数组;


如果source为字符串,则按照指定的encoding将字符串转换为字节序列;


如果source为可迭代类型,则元素必须为[0 ,255]中的整数;


如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.。


版本:在python2.6后新引入,在python3中同样可以使用




Conversions between Various Formats
 
 

Convert between Python tuple and list

a = (1, 2)      # a is a tuple 
b = list(a)     # b is a list 
c = tuple(b)  # c is a tuple 

Convert between Python tuple, list and NumPy 1D array 

a = (1, 2)          # a is a tuple 
b = np.array(a)  # b is an numpy array 
c = tuple(b)       # c is a tuple 

a = [1, 2]          # a is a python array 
b = np.array(a)  # b is a numpy array 
c = list(b)          # c is a python list 

Convert between NumPy 2D array and NumPy matrix

a = numpy.ndarray([2,3])   # create 2x3 array
m1 = numpy.asmatrix(a)   # does not create new matrix, m1 refers to the same memory as a 
m2 = numpy.matrix(a)      # creates new matrix and copies content 

b1 = numpy.asarray(m2)   # does not create array, b1 refers to the same memory as m2
b2 = numpy.array(m2)      # creates new array and copies content 
 

  Read/Write Images with OpenCV

image = cv.LoadImage(“ponzo.jpg”)
cv.SaveImage(“out.png”, image)

Read/Write Images with PIL


image = Image.open(“ponzo.jpg”)
image.save(“out.jpg”)

Read/Write Images with PyOpenCV

mat = pyopencv.imread(“ponzo.jpg”)
pyopencv.imwrite(“out.png”, mat)
 
 

Convert between OpenCV image and PIL image

# color image 
cimg = cv.LoadImage("ponzo.jpg", cv.CV_LOAD_IMAGE_COLOR)     # cimg is a OpenCV image
pimg = Image.fromstring("RGB", cv.GetSize(cimg), cimg.tostring())    # pimg is a PIL image 
cimg2 = cv.CreateImageHeader(pimg.size, cv.IPL_DEPTH_8U, 3)      # cimg2 is a OpenCV image 
cv.SetData(cimg2, pimg.tostring())

Note: OpenCV stores color image in BGR format. So, the converted PIL image is also in BGR-format. The standard PIL image is stored in RGB format. 

# gray image 
cimg = cv.LoadImage("ponzo.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE)   # cimg is a OpenCV image 
pimg = Image.fromstring("L", cv.GetSize(cimg), cimg.tostring())                 # pimg is a PIL image 
cimg2 = cv.CreateImageHeader(pimg.size, cv.IPL_DEPTH_8U, 1)              # cimg2 is a OpenCV image
cv.SetData(cimg2, pimg.tostring())
 

 

Convert between PIL image and NumPy ndarray

image = Image.open(“ponzo.jpg”)   # image is a PIL image 
array = numpy.array(image)          # array is a numpy array 
image2 = Image.fromarray(array)   # image2 is a PIL image 

Convert between PIL image and PyOpenCV matrix

image = Image.open(“ponzo.jpg”)                  # image is a PIL image
mat = pyopencv.Mat.from_pil_image(image)  # mat is a PyOpenCV matrix 
image2 = mat.to_pil_image()                        # image2 is a PIL image 
 

  Convert between OpenCV image and NumPy ndarray

cimg = cv.LoadImage("ponzo.jpg", cv.CV_LOAD_IMAGE_COLOR)   # cimg is a OpenCV image 
pimg = Image.fromstring("RGB", cv.GetSize(cimg), cimg.tostring())  # pimg is a PIL image 
array = numpy.array(pimg)     # array is a numpy array 
pimg2 = cv.fromarray(array)    # pimg2 is a OpenCV image

-------------------------------------------------------------------------------------------------------------
1. opencv  videoWriter写视频文件

# Create video writer object
vidwrite = cv2.VideoWriter(['testvideo', cv2.cv.CV_FOURCC('M','J','P','G'), 25, 
               (640,480),True])
注意到如果要写成功有几个因素需要注意:
 (1) 必须安装了ffmpeg或者Gstreamer
 (2) 摄像头的配置参数必须和写文件的参数一致,注意的是width,height,是width在前
    cap = cv2.VideoCapture(0)
    cap.set(1,20.0)
    cap.set(3,640)
    cap.set(4,480)
    fourcc = cv2.cv.FOURCC('M','J','P','G')
    videoW = cv2.VideoWriter('d.avi',fourcc,20.0,(640,480),True)
    while(True):
        ret,frame = cap.read()
        cv2.imshow('frame',frame)
        videoW.write(frame)
        if cv2.waitKey(1) & 0xff == ord('q'):
            break
    videoW.release() 
    cap.release()
    cv2.destroyAllWindows()


也可以使用:

# The following might fail if the device doesn't support these values
cap.set(1, 20.0) #Match fps
cap.set(3,640)   #Match width
cap.set(4,480)   #Match height

# So it's always safer to retrieve it afterwards
fps = cap.get(CV_CAP_PROP_FPS)
w = cap.get(CV_CAP_PROP_FRAME_WIDTH);
h = cap.get(CV_CAP_PROP_FRAME_HEIGHT);

2. opencv画直线等
注意到这些函数都是不支持分数像素精度的,只是支持整数point的输入。
http://s4/mw690/002mfkyxgy70zvMkzcLe3&690PIL 图像处理模块以及array的互相转换,基本图像处理收集" TITLE="python PIL 图像处理模块以及array的互相转换,基本图像处理收集" />






0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有