【问题标题】:only rotate part of image python只旋转图像python的一部分
【发布时间】:2017-01-04 10:03:38
【问题描述】:

谁能告诉我如何像这样只旋转图像的一部分:

如何找到这张图片的坐标/中心:

我可以使用这个旋转所有图片

from PIL import Image

def rotate_image():
img = Image.open("nime1.png")

img.rotate(45).save("plus45.png")
img.rotate(-45).save("minus45.png")

img.rotate(90).save("90.png")
img.transpose(Image.ROTATE_90).save("90_trans.png")

img.rotate(180).save("180.png")


if __name__ == '__main__':
rotate_image()

【问题讨论】:

  • 尝试在您的问题中包含图片而不链接到它。
  • 完成先生,this image
  • 复制图片;裁剪到要旋转的所需区域,旋转它,然后将其粘贴到原件上。这行得通吗?
  • 我尝试使用this 答案,但我得到了错误:(

标签: python image rotation python-imaging-library python-3.4


【解决方案1】:

您可以将图片的某个区域裁剪为新变量。在这种情况下,我从原始图像中裁剪了一个 120x120 像素的框。它旋转 90 度,然后粘贴回原件上。

from PIL import Image

img = Image.open('./image.jpg')
sub_image = img.crop(box=(200,0,320,120)).rotate(90)
img.paste(sub_image, box=(200,0))

所以我对此进行了更多思考,并制作了一个函数,在旋转之前将圆形蒙版应用于裁剪的图像。这允许任意角度而不会产生奇怪的效果。

def circle_rotate(image, x, y, radius, degree):
    img_arr = numpy.asarray(image)
    box = (x-radius, y-radius, x+radius+1, y+radius+1)
    crop = image.crop(box=box)
    crop_arr = numpy.asarray(crop)
    # build the cirle mask
    mask = numpy.zeros((2*radius+1, 2*radius+1))
    for i in range(crop_arr.shape[0]):
        for j in range(crop_arr.shape[1]):
            if (i-radius)**2 + (j-radius)**2 <= radius**2:
                mask[i,j] = 1
    # create the new circular image
    sub_img_arr = numpy.empty(crop_arr.shape ,dtype='uint8')
    sub_img_arr[:,:,:3] = crop_arr[:,:,:3]
    sub_img_arr[:,:,3] = mask*255
    sub_img = Image.fromarray(sub_img_arr, "RGBA").rotate(degree)
    i2 = image.copy()
    i2.paste(sub_img, box[:2], sub_img.convert('RGBA'))
    return i2

i2 = circle_rotate(img, 260, 60, 60, 45)
i2

【讨论】:

  • 是的,先生,成功了,但我无法保存新图片:(
  • 先生为什么我不成功,如果我尝试使用 circle_rotate
  • 您可以使用i2.save('./new_image.jpg')保存图片
  • sir iam 使用 SC 进行旋转,但无法在 i2 = circle_rotate(img, 260, 60, 60, 45) 中出错 :( 如果我将使用 SC 输入图像的代码在哪里?跨度>
【解决方案2】:

您可以这样解决这个问题。假设你有img = Image.open("nime1.png")

  1. 使用 img2 = img.copy() 创建图像的副本
  2. 使用 img2.crop() 在所需位置创建 img2 的裁剪。你可以阅读如何做到这一点here
  3. 使用 img.paste() 将 img2 粘贴回 img 的适当位置

注意事项:

要找到中心坐标,可以将宽度和高度除以 2 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2013-07-24
    相关资源
    最近更新 更多