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

Art*_*nov 4 python opencv image crop image-processing

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

在此处输入图片说明

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

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)
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

cv2.HoughCircles()似乎产生None而不是裁剪的圆形阵列。我该如何解决?

fur*_*ras 5

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


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

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


我为此使用模块PIL/ pillow

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

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

最后,我将此图像作为 Alpha 通道添加到裁剪后的图像并将其另存为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()
Run Code Online (Sandbox Code Playgroud)

结果

在此处输入图片说明


顺便提一句:

在掩码中,您可以使用 0 到 255 之间的值,并且不同的像素可能具有不同的透明度 - 其中一些可以是半透明的以制作平滑的边框。

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


编辑:在面具上有更多圆圈的例子。

在此处输入图片说明

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()
Run Code Online (Sandbox Code Playgroud)