gpt4 book ai didi

python - 从图像中裁剪圆形缩略图的最简单方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:55 24 4
gpt4 key购买 nike

我正在尝试从此图像中裁剪一个居中(或不居中)的圆:

enter image description here

我从关于堆栈溢出的这个主题的现有问题中窃取了这段代码,但出了点问题:

import cv2

file = 'dog.png'

img = cv2.imread(file)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
circle = cv2.HoughCircles(img,
3,
dp=1.5,
minDist=10,
minRadius=1,
maxRadius=10)
x = circle[0][0][0]
y = circle[0][0][1]
r = circle[0][0][2]

rectX = (x - r)
rectY = (y - r)
crop_img = img[rectY:(rectY+2*r), rectX:(rectX+2*r)]
cv2.imwrite('dog_circle.png', crop_img)

输出:

Traceback (most recent call last):
File "C:\Users\Artur\Desktop\crop_circle - Kopie\crop_circle.py", line 14, in <module>
x = circle[0][0][0]
TypeError: 'NoneType' object is not subscriptable

cv2.HoughCircles() 似乎生成 None 而不是裁剪的圆形数组。我该如何解决这个问题?

最佳答案

首先:HoughCircles 用于检测图像上的圆圈,而不是裁剪它。


你不能有圆形图片。图像始终是矩形,但某些像素可以是透明的(RGBA 中的 alpha channel )并且程序不会显示它们。

因此,您可以先裁剪图像以使其具有正方形,然后添加包含哪些像素应该可见的信息的 alpha channel 。在这里,您可以使用黑色背景上带有白色圆圈的蒙版。最后,您必须将其保存为 pngtiff,因为 jpg 无法保留 alpha channel 。


我为此使用模块 PIL/pillow

我在图像中心裁剪正方形区域,但您可以为此使用不同的坐标。

接下来我创建具有相同大小和黑色背景的灰度图像并绘制白色圆/椭圆。

最后,我将这张图片作为 alpha channel 添加到裁剪后的图片中,并将其保存为 png

from PIL import Image, ImageDraw

filename = 'dog.jpg'

# load image
img = Image.open(filename)

# crop image
width, height = img.size
x = (width - height)//2
img_cropped = img.crop((x, 0, x+height, height))

# create grayscale image with white circle (255) on black background (0)
mask = Image.new('L', img_cropped.size)
mask_draw = ImageDraw.Draw(mask)
width, height = img_cropped.size
mask_draw.ellipse((0, 0, width, height), fill=255)
#mask.show()

# add mask as alpha channel
img_cropped.putalpha(mask)

# save as png which keeps alpha channel
img_cropped.save('dog_circle.png')

img_cropped.show()

结果

enter image description here


顺便说一句:

在蒙版中,您可以使用 0 到 255 之间的值,不同的像素可能具有不同的透明度 - 其中一些可以是半透明的,以形成平滑的边框。

如果您想在自己页面的 HTML 中使用它,则不必创建圆形图像,因为 Web 浏览器可以将图像的角圆化并将其显示为圆形。为此,您必须使用 CSS。


编辑:蒙版上有更多圆圈的示例。

enter image description here

from PIL import Image, ImageDraw

filename = 'dog.jpg'

# load image
img = Image.open(filename)

# crop image
width, height = img.size
x = (width - height)//2
img_cropped = img.crop((x, 0, x+height, height))

# create grayscale image with white circle (255) on black background (0)
mask = Image.new('L', img_cropped.size)
mask_draw = ImageDraw.Draw(mask)
width, height = img_cropped.size
mask_draw.ellipse((50, 50, width-50, height-50), fill=255)
mask_draw.ellipse((0, 0, 250, 250), fill=255)
mask_draw.ellipse((width-250, 0, width, 250), fill=255)

# add mask as alpha channel
img_cropped.putalpha(mask)

# save as png which keeps alpha channel
img_cropped.save('dog_2.png')

img_cropped.show()

关于python - 从图像中裁剪圆形缩略图的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58543750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com