繁体   English   中英

如何在不改变图像分辨率的情况下使用 OpenCV 或 Python 中的 PIL 使形状变大或变小

[英]How to make a shape larger or smaller without changing the resolution of the image using OpenCV or PIL in Python

我希望能够在 PIL 图像或 OpenCV 图像中制作特定形状 3 倍大和小而不改变图像的分辨率或改变我想要变大的形状的形状。 我尝试过使用 OpenCV 的膨胀方法,但这不是它的预期用途,而且它改变了图像的形状。 例如:

在此处输入图像描述

谢谢。

这是一种方法:

  • 找到有趣的形状,即非白色 ROI 区域
  • 提取它
  • 按比例放大
  • 将原始图像清除为白色
  • 将缩放的 ROI 粘贴回具有相同中心的图像中

#!/usr/bin/env python3

import cv2
import numpy as np

if __name__ == "__main__":

    # Open image
    orig = cv2.imread('image.png',cv2.IMREAD_COLOR)

    # Get extent of interesting part, i.e. non-white part
    y, x, _ = np.nonzero(~orig)
    y0, y1 = np.min(y), np.max(y)    # top and bottom rows
    x0, x1 = np.min(x), np.max(x)    # left and right cols
    h, w = y1-y0, x1-x0              # height and width
    ROI = orig[y0:y1, x0:x1]         # extract ROI
    cv2.imwrite('ROI.png', ROI)      # DEBUG only

    # Upscale ROI
    factor = 3
    scaledROI = cv2.resize(ROI, (w*factor,h*factor), interpolation=cv2.INTER_NEAREST)
    newH, newW = scaledROI.shape[:2]

    # Clear original image to white
    orig[:] = [255,255,255]

    # Get centre of original shape, and position of top-left of ROI in output image
    cx, cy = (x0 + x1) //2, (y0 + y1)//2
    top  = cy - newH//2
    left = cx - newW//2

    # Paste in rescaled ROI
    orig[top:top+newH, left:left+newW] = scaledROI
    cv2.imwrite('result.png', orig)

这改变了这一点:

在此处输入图像描述

对此:

在此处输入图像描述

让我想起了受电弓:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM