实用笔记系列2

  • 获取图片Exif旋转信息并旋转图片
    import cv2
    from PIL import Image, ExifTags
    def img_ratation(image, angle):
        """
        """
        # grab the dimensions of the image and then determine the
        # center
        (h, w) = image.shape[:2]
        (cX, cY) = (w // 2, h // 2)
        # grab the rotation matrix (applying the negative of the
        # angle to rotate clockwise), then grab the sine and cosine
        # (i.e., the rotation components of the matrix)
        M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
        cos = np.abs(M[0, 0])
        sin = np.abs(M[0, 1])
        # compute the new bounding dimensions of the image
        nW = int((h * sin) + (w * cos))
        nH = int((h * cos) + (w * sin))
        # adjust the rotation matrix to take into account translation
        M[0, 2] += (nW / 2) - cX
        M[1, 2] += (nH / 2) - cY
        # perform the actual rotation and return the image
        return cv2.warpAffine(image, M, (nW, nH))
        
    def img_rotation_correction(fpath):
        """
        获取文件的旋转角度信息并矫正
        """
        angle = 0
        cv_img = None
        try:
            img = Image.open(fpath)
            detect_orientation_info = False
            for orientation in ExifTags.TAGS.keys() : 
                if ExifTags.TAGS[orientation]=='Orientation':
                    detect_orientation_info=True
                    break
    
            if detect_orientation_info and img._getexif(): 
                exif=dict(img._getexif().items())
                if exif[orientation] == 3 : # 180
                    angle = 180
                elif exif[orientation] == 6 : # 顺时针90°
                    angle = 270
                elif exif[orientation] == 8 : # 逆时针90°
                    angle = 90
        except Exception as e:
            print(f"correct error:{e}")
        finally:
            cv_img = cv2.imread(fpath)
            if angle:
                cv_img = img_ratation(cv_img, angle)
            
            return cv_img
    
  • datetime毫秒级时间统计
import datetime
start_time = datetime.datetime.now()
end_time = datetime.datetime.now()
strTime = 'total cost time use:%dms' % ((end_time -start_time).seconds * 1000 + (end_time -start_time).microseconds / 1000)
  • 获取当前路径
import os, sys
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(BASE_DIR)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

血_影

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值