Boost.Python.ArgumentError: Image.__init__(Image, file) 的Python参数类型与C++签名不匹配
下面是用Python代码从图片中去除背景的例子。我按照这个链接 https://pypi.python.org/pypi/pgmagick/ 上的步骤,在Mac OS X Mavericks上安装了pgmagick。
import pgmagick as pg
def trans_mask_sobel(img):
""" Generate a transparency mask for a given image """
image = pg.Image(img)
# Find object
image.negate()
image.edge()
image.blur(1)
image.threshold(24)
image.adaptiveThreshold(5, 5, 5)
# Fill background
image.fillColor('magenta')
w, h = image.size().width(), image.size().height()
image.floodFillColor('0x0', 'magenta')
image.floodFillColor('0x0+%s+0' % (w-1), 'magenta')
image.floodFillColor('0x0+0+%s' % (h-1), 'magenta')
image.floodFillColor('0x0+%s+%s' % (w-1, h-1), 'magenta')
image.transparent('magenta')
return image
def alpha_composite(image, mask):
""" Composite two images together by overriding one opacity channel """
compos = pg.Image(mask)
compos.composite(
image,
image.size(),
pg.CompositeOperator.CopyOpacityCompositeOp
)
return compos
def remove_background(filename):
""" Remove the background of the image in 'filename' """
img = pg.Image(filename)
transmask = trans_mask_sobel(img)
img = alphacomposite(transmask, img)
img.trim()
img.write('out.png')
img = open("example.jpg")
remove_background(img)
在运行这个代码的时候,我遇到了以下错误
Traceback (most recent call last):
File "imgrm.py", line 48, in <module>
remove_background(img)
File "imgrm.py", line 41, in remove_background
img = pg.Image(filename)
Boost.Python.ArgumentError: Python argument types in
Image.__init__(Image, file)
did not match C++ signature:
__init__(_object*, Magick::Image)
__init__(_object*, unsigned int, unsigned int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, MagickLib::StorageType, char const*)
__init__(_object*, Magick::Blob, Magick::Geometry, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
__init__(_object*, Magick::Blob, Magick::Geometry, unsigned int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
__init__(_object*, Magick::Blob, Magick::Geometry, unsigned int)
__init__(_object*, Magick::Blob, Magick::Geometry)
__init__(_object*, Magick::Blob)
__init__(_object*, Magick::Geometry, Magick::Color)
__init__(_object*, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
__init__(_object*)
这是什么问题?我该怎么解决呢?
2 个回答
0
错误信息看起来可能有点复杂,因为里面有很多C++类型的名字。不过,它告诉我们,pgmagick.Image
在尝试用一个file
对象来创建一个实例,但实际上,pgmagick并没有提供一个可以接受file
对象的__init__
方法。
在这种情况下,remove_background()
方法的filename
参数需要的是一个str
(字符串),而不是file
。要解决这个问题,可以把:
img = open("example.jpg")
remove_background(img)
改成:
remove_background("example.jpg")
1
我也遇到了和pgmagick
一样的问题,下面的代码帮我解决了这个问题:
image = pg.Image(str(img))