python中PIL.Image和OpenCV圖像格式相互轉換

PIL.Image轉換成OpenCV格式:

 

[python] view plain copy

 

  1. import cv2  
  2. from PIL import Image  
  3. import numpy  
  4.   
  5. image = Image.open("plane.jpg")  
  6. image.show()  
  7. img = cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR)  
  8. cv2.imshow("OpenCV",img)  
  9. cv2.waitKey()  


 

 

OpenCV轉換成PIL.Image格式:

 

[python] view plain copy

 

  1. import cv2  
  2. from PIL import Image  
  3. import numpy  
  4.   
  5. img = cv2.imread("plane.jpg")  
  6. cv2.imshow("OpenCV",img)  
  7. image = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))  
  8. image.show()  
  9. cv2.waitKey()  

 

 

判斷圖像數據是否是OpenCV格式:

isinstance(img, np.ndarray)

 

 

 

 

PIL(RGB)

首先介紹PIL(Python Imaging Library)這個庫,這是Python中最基礎的圖像處理庫,主要注意對圖片進行處理時w,h的變化


 
  1. from PIL import Image

  2. import numpy as np

  3. image = Image.open('test.jpg') # 圖片是400x300 寬x高

  4. print type(image) # out: PIL.JpegImagePlugin.JpegImageFile

  5. print image.size # out: (400,300)

  6. print image.mode # out: 'RGB'

  7. print image.getpixel((0,0)) # out: (143, 198, 201)

  8. # resize w*h

  9. image = image.resize((200,100),Image.NEAREST)

  10. print image.size # out: (200,100)

  11. '''

  12. 代碼解釋

  13. **注意image是 class:`~PIL.Image.Image` object**,它有很多屬性,比如它的size是(w,h),通道是RGB,,他也有很多方法,比如獲取getpixel((x,y))某個位置的像素,得到三個通道的值,x最大可取w-1,y最大可取h-1

  14. 比如resize方法,可以實現圖片的放縮,具體參數如下

  15. resize(self, size, resample=0) method of PIL.Image.Image instance

  16. Returns a resized copy of this image.

  17.  
  18. :param size: The requested size in pixels, as a 2-tuple:

  19. (width, height).

  20. 注意size是 (w,h),和原本的(w,h)保持一致

  21. :param resample: An optional resampling filter. This can be

  22. one of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BOX`,

  23. :py:attr:`PIL.Image.BILINEAR`, :py:attr:`PIL.Image.HAMMING`,

  24. :py:attr:`PIL.Image.BICUBIC` or :py:attr:`PIL.Image.LANCZOS`.

  25. If omitted, or if the image has mode "1" or "P", it is

  26. set :py:attr:`PIL.Image.NEAREST`.

  27. See: :ref:`concept-filters`.

  28. 注意這幾種插值方法,默認NEAREST最近鄰(分割常用),分類常用BILINEAR雙線性,BICUBIC立方

  29. :returns: An :py:class:`~PIL.Image.Image` object.

  30.  
  31. '''

  32. image = np.array(image,dtype=np.float32) # image = np.array(image)默認是uint8

  33. print image.shape # out: (100, 200, 3)

  34. # 神奇的事情發生了,w和h換了,變成(h,w,c)了

  35. # 注意ndarray中是 行row x 列col x 維度dim 所以行數是高,列數是寬

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

Skimage(RGB)

skimage即是Scikit-Image,官網


 
  1. import skimage

  2. from skimage import io,transform

  3. import numpy as np

  4. image= io.imread('test.jpg',as_grey=False)

  5. # 第一個參數是文件名可以是網絡地址,第二個參數默認爲False,True時爲灰度圖

  6. print type(image) # out: numpy.ndarray

  7. print image.dtype # out: dtype('uint8')

  8. print image.shape # out: (300, 400, 3) (h,w,c)前面介紹了ndarray的特點

  9. # mode也是RGB

  10. print image

  11. '''

  12. 注意此時image裏都是整數uint8,範圍[0-255]

  13. array([

  14. [ [143, 198, 201 (dim=3)],[143, 198, 201],... (w=200)],

  15. [ [143, 198, 201],[143, 198, 201],... ],

  16. ...(h=100)

  17. ], dtype=uint8)

  18.  
  19. '''

  20. image= io.imread('test.jpg',as_grey=True)

  21. print image.shape # out: (300, 400)

  22. print image

  23. '''

  24. 此時image範圍變爲[0-1]

  25. array([[ 0.73148549, 0.73148549, 0.73148549, ..., 0.73148549,

  26. 0.73148549, 0.73148549],

  27. [ 0.73148549, 0.73148549, 0.73148549, ..., 0.73148549,

  28. .....]])

  29. '''

  30. print image.dtype # out: dtype('float64')

  31.  
  32. image = io.imread('test.jpg',as_grey=False)

  33. # h*w

  34. image = transform.resize(image,(100, 200),order=1) # order默認是1,雙線性

  35. #resize後image範圍又變成[0-1]

  36. print image.dtype # out: dtype('float64')

  37. print image.shape # out: (100, 200, 3)

  38. print image

  39. '''

  40. array([[[ 0.56078431, 0.77647059, 0.78823529],

  41. [ 0.56078431, 0.77647059, 0.78823529],

  42. [ 0.56078431, 0.77647059, 0.78823529],

  43. ..., ...]])

  44. '''

  45. '''

  46. resize函數接口

  47. resize(image, output_shape, order=1, mode='constant', cval=0, clip=True, preserve_range=False)

  48. order : int, optional

  49. The order of interpolation. The order has to be in the range 0-5:

  50. - 0: Nearest-neighbor

  51. - 1: Bi-linear (default)

  52. - 2: Bi-quadratic

  53. - 3: Bi-cubic

  54. - 4: Bi-quartic

  55. - 5: Bi-quintic

  56.  
  57. '''

  58. print skimage.img_as_float(image).dtype # out: float64

  59. # img_as_float可以把image轉爲double,即float64

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59

OpenCV(python版)(BGR)

OpenCV是個很強大的圖像處理庫,性能也很好。


 
  1. import cv2

  2. import numpy as np

  3. image = cv2.imread('test.jpg')

  4. print type(image) # out: numpy.ndarray

  5. print image.dtype # out: dtype('uint8')

  6. print image.shape # out: (300, 400, 3) (h,w,c) 和skimage類似

  7. print image # BGR

  8. '''

  9. array([

  10. [ [143, 198, 201 (dim=3)],[143, 198, 201],... (w=200)],

  11. [ [143, 198, 201],[143, 198, 201],... ],

  12. ...(h=100)

  13. ], dtype=uint8)

  14.  
  15. '''

  16. # w*h

  17. image = cv2.resize(image,(100,200),interpolation=cv2.INTER_LINEAR)

  18. print image.dtype # out: dtype('uint8')

  19. print image.shape # out: (200, 100, 3)

  20. '''

  21. 注意注意注意 和skimage不同

  22. resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])

  23. 關鍵字參數爲dst,fx,fy,interpolation

  24. dst爲縮放後的圖像

  25. dsize爲(w,h),但是image是(h,w,c)

  26. fx,fy爲圖像x,y方向的縮放比例,

  27. interplolation爲縮放時的插值方式,有三種插值方式:

  28. cv2.INTER_AREA:使用象素關係重採樣。當圖像縮小時候,該方法可以避免波紋出現。當圖像放大時,類似於 CV_INTER_NN方法    

  29. cv2.INTER_CUBIC: 立方插值

  30. cv2.INTER_LINEAR: 雙線形插值 

  31. cv2.INTER_NN: 最近鄰插值

  32. [詳細可查看該博客](http://www.tuicool.com/articles/rq6fIn)

  33. '''

  34. '''

  35. cv2.imread(filename, flags=None):

  36. flag:

  37. cv2.IMREAD_COLOR 1: Loads a color image. Any transparency of image will be neglected. It is the default flag. 正常的3通道圖

  38. cv2.IMREAD_GRAYSCALE 0: Loads image in grayscale mode 單通道灰度圖

  39. cv2.IMREAD_UNCHANGED -1: Loads image as such including alpha channel 4通道圖

  40. 注意: 默認應該是cv2.IMREAD_COLOR,如果你cv2.imread('gray.png'),雖然圖片是灰度圖,但是讀入後會是3個通道值一樣的3通道圖片

  41.  
  42. '''

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

在進行圖像處理時一點要注意 各個庫之間的細微差異,還有要注意圖像放縮時插值方法的選擇,而且即使是相同的插值方法,各個庫的實現也不同,結果也會有些許差異。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章