借助numpy.rot90实现图片顺时针旋转90°,旋转后图片没有黑边

本文介绍了如何将numpy图片从BGR通道转换为RGB,并展示了长方形图片旋转后坐标变换的算法,包括点位移计算。重点在于图像处理和坐标变换技巧在实际项目中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 返回numpy 类型图片, numpy 通道是 “BGR”

import cv2
import glob
import numpy as np
from PIL import Image
imagelist = glob.glob('*.jpg')
for imagename in imagelist:
    image = Image.open(imagename)
    image = np.asarray(image)
    rotated = np.rot90(image, 3)

    # 通道转换
    r, g, b = rotated[:, :, 0], rotated[:, :, 1], rotated[:, :, 2]
    h, w = r.shape
    new = np.zeros((h, w, 3))
    new[:, :, 0] = b
    new[:, :, 1] = g
    new[:, :, 2] = r

    cv2.imwrite(imagename, new)

返回Image类型图片, Image 通道是 “RGB”

# 旋转图片,没有黑边
def rotateImage(img):
    image = np.asarray(img)
    rotated = np.rot90(image)   # 逆时针旋转!

    newimage = Image.fromarray(np.uint8(rotated))
    return newimage

长方形图片对应的坐标变换

def processPoints(pointList, fw, fh):
    '''
        fw, fh 分别为图片旋转前的宽度和长度
        pointList为标注点列表,格式:[[x0, y0], [x1, y1], [x2, y2], ...]
    '''

    pointlist = []

    for point in pointList:
       # 旋转
       """
            长方形图片,旋转后无黑边,对应点坐标变换:
            求点point1绕点point2旋转angle后的点坐标
            ======================================
            在平面坐标上,任意点P(x1,y1),绕一个坐标点Q(x2,y2)旋转θ角度后,新的坐标设为(x, y)的计算公式:
            x= (x1 - x2)*cos(θ) - (y1 - y2)*sin(θ) + y2 ;
            y= (x1 - x2)*sin(θ) + (y1 - y2)*cos(θ) + x2 ;
            ======================================
            将图像坐标(x,y)转换到平面坐标(x`,y`):
            x`=x
            y`=height-y
            :param point1: 被旋转的点
            :param point2: base point (基点)
            :param angle: 旋转角度,弧度制表示!不是数字表示!正:表示逆时针,负:表示顺时
        """
        x1, y1 = point[0], point[1]
        rotx, roty = fw // 2, fh // 2

        # 将图像坐标转换到平面坐标
        y1 = fh - y1
        roty = fh - roty

        # 逆时针
        import math
        x = (x1 - rotx) * math.cos(math.pi/2) - (y1 - roty) * math.sin(math.pi/2) + roty
        y = (x1 - rotx) * math.sin(math.pi/2) + (y1 - roty) * math.cos(math.pi/2) + rotx

        # 旋转后,长和宽对调
        fw, fh = fh, fw

        # 将平面坐标转换到图像坐标
        y = fh - y

        pointlist.append([int(x), int(y)])

    if len(pointlist) == 0:
        return pointList

    return pointlist

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值