python opencv、PIL笔记

1、中文字符文件名处理

读、写文件:

  image = cv2.imread('xxx.jpg')

  cv2.imwrite('xxx.jpg', image)

 

  image type :  <class 'numpy.ndarray'>

  height = image.shape[0]

       width = image.shape[1]

  image.size(height * width * channel)

如果文件名或路径含中文,则:

  image = cv2.imdecode(np.fromfile(‘xxx.jpg’, dtype=np.uint8), -1)

  cv2.imencode('.jpg', image)[1].tofile(file_name)

2、彩色图转换为灰度图

  image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

3、PIL

  image = Image.open(img_path)

 img.size  #图片的尺寸
 img.mode  #图片的模式  RGBA
 img.format  #图片的格式  PNG

  width = image.size[0]

  height = image.size[1]

  ## RGBA 转 RGB 1

  img=Image.open(r'G:\下载 (1).png')

  img=img.convert('RGB')

  ## RGBA 转 RGB 2

  img = Image.open(r'G:\下载 (1).png')
  bg = Image.new("RGB", img.size, (255,255,255))
  bg.paste(img,img)
  bg.save(r'G:\1.jpg')

4、RGB转BGR

  def img_rgb2_bgr(img):

    return img[: , : , : : -1]

  img = cv2.imread(r'G:\1.jpg')
  img = img[: , : , : : -1]
  cv2.imwrite(r'G:\1111.jpg', img)

  

  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

 

  img = Image.open(r'G:\下载 (1).png')
  bg = Image.new("RGB", img.size, (255,255,255))
  bg.paste(img,img)

  bg = numpy.array(bg)
  bg = bg[: , : , : : -1]

  # 裁剪,height的范围10~200,width范围20~250

  bg = bg[10:200, 20:250]

  bg = Image.fromarray(bg)
  bg.save(r'G:\1x.jpg')

 

#PIL--->OpenCV
image=Image.open('color.png')   
img=cv2.cvtColor(numpy.asarray(image),cv2.COLOR_RGB2BGR) 

 

5、随机图片

import numpy as np
import cv2

# 图片的分辨率为200*300,这里b, g, r设为随机值,注意dtype属性
b = np.random.randint(0, 255, (200, 300), dtype=np.uint8)
g = np.random.randint(0, 255, (200, 300), dtype=np.uint8)
r = np.random.randint(0, 255, (200, 300), dtype=np.uint8)

# 合并通道,形成图片
img = cv2.merge([b, g, r])
image=Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))  
image.show()

 

posted @ 2019-08-03 19:36  碧水青山  阅读(696)  评论(0编辑  收藏  举报