读写包含中文文件名的图片

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import cv2
import glob
import numpy as np

def read_image(path):
    return cv2.imdecode(np.fromfile(path, dtype=np.uint8), cv2.IMREAD_UNCHANGED)


def save_image(path, img):
    cv2.imencode(".jpg", img)[1].tofile(path)

图片旋转

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import cv2

def rotateAndScale(img, scaleFactor=1.0, degreesCCW=30, borderValue=(255,255,255)):
    oldY, oldX = img.shape[:2]
    M = cv2.getRotationMatrix2D(center=(oldX / 2, oldY / 2), angle=degreesCCW, scale=scaleFactor)

    newX, newY = oldX * scaleFactor, oldY * scaleFactor
    r = np.deg2rad(degreesCCW)
    newX, newY = (abs(np.sin(r) * newY) + abs(np.cos(r) * newX), abs(np.sin(r) * newX) + abs(np.cos(r) * newY))

    (tx, ty) = ((newX - oldX) / 2, (newY - oldY) / 2)
    M[0, 2] += tx
    M[1, 2] += ty

   return cv2.warpAffine(img, M, dsize=(int(newX), int(newY)), borderValue=borderValue)