【问题标题】:Drawing an image with specific location, size and rotation绘制具有特定位置、大小和旋转的图像
【发布时间】:2017-10-07 06:56:28
【问题描述】:

有没有办法快速绘制具有特定位置、大小和旋转的图像?假设我有一个框架,我想在它上面绘制一个带有某些变换的图像,我该怎么做呢?图片会有一个 alpha 通道,所以我不能直接复制它:

image = # a loaded image
x, y, w, h = # some values

# resize
cv2.resize(image, (w, h))
# rotation
# ???
frame[y:y+h,x:x+w] = image

这也不适用旋转。

我可以从 OpenCV 中使用任何快速的方法吗?如果没有,我应该如何实现?

【问题讨论】:

  • PyGame 和 TKinter 支持旋转。
  • 您可以使用getRotationMatrix 加上warpAffine 来旋转图像。将旋转的图像粘贴到框架上更棘手....最简单的方法是使用旋转图像的 alpha 通道(实际图像上为 255,旋转产生的背景为 0)并手动复制到框架中具有 255 个 Alpha 通道的像素

标签: python image opencv


【解决方案1】:

由于似乎没有快速的方法,我创建了这个函数来实现这个效果:

import numpy as np
import imutils
import cv2

def draw(frame, image, location, dimension, rotation=0):
    w, h = dimension    # dimension
    x, y = location     # center

    fh, fw = frame.shape[:2]    # frame size

    image = cv2.resize(image, (w, h))               # resize image
    image = imutils.rotate_bound(image, rotation)   # rotate image

    nh, nw = image.shape[:2]
    tlx, tly = x - nw / 2, y - nh / 2   # top left

    if tlx < 0:
        # x left out of bound
        offset = (0 - tlx)
        nw -= offset
        tlx = 0
        image = image[:,offset:,:]
    if tlx + nw >= fw:
        # x right out of bound
        offset = (tlx + nw - fw)
        nw -= offset
        image = image[:,:nw,:]
    if tly < 0:
        # y left out of bound
        offset = (0 - tly)
        nh -= offset
        tly = 0
        image = image[offset:,:,:]
    if tly + nh >= fh:
        # y right out of bound
        offset = (tly + nh - fh)
        nh -= offset
        image = image[:nh,:,:]

    overlay_img = image[:,:,:3]         # RGB channel
    overlay_alpha = cv2.split(image)[3] # alpha channel

    res, overlay_is_alpha = cv2.threshold(overlay_alpha, 10, 1, cv2.THRESH_BINARY_INV)  # 1 if alpha, 0 if not
    res, overlay_is_not_alpha = cv2.threshold(overlay_alpha, 10, 1, cv2.THRESH_BINARY)  # 0 if alpha, 1 if not
    overlay_is_alpha = np.repeat(overlay_is_alpha, 3).reshape((nh,nw,3))                # expand to all 4 channels
    overlay_is_not_alpha = np.repeat(overlay_is_not_alpha, 3).reshape((nh,nw,3))

    overlay_img *= overlay_is_not_alpha                 # mask out alpha pixels
    frame[tly:tly+nh, tlx:tlx+nw] *= overlay_is_alpha   # mask out non alpha pixels

    frame[tly:tly+nh, tlx:tlx+nw] += overlay_img    # combine
draw(
    bg,         # background image in BGR
    image,      # image to be drawn in BGRA
    location,   # center (x,y)
    dimension,  # size (w,h)
    degree      # rotation (deg)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多