在新的较大图像上复制图像

时间:2013-02-20 14:25:17

标签: python opencv image-processing numpy

我有一个彩色图像sourceImage,我会将此图像复制到一个新的较大的彩色图像destImage上:源图像应居中于新图像上。为了执行此过程,我编写了以下代码:

destHeight :新较大图片的高度 destWidth :新较大图片的宽度

sourceFilename :源图像的路径

sourceImage = cv2.imread(sourceFilename,1)
imgHeight, imgWidth, imgChannels = sourceImage.shape[:3]
#print sourceImage.shape[:3]

destImage = np.zeros((destHeight,destWidth,imgChannels), np.uint8)
#print destImage.shape[:3]

yBorder = (destHeight-imgHeight)/2
xBorder = (destWidth-imgWidth)/2
#print yBorder, xBorder

destImage[yBorder:imgHeight,xBorder:imgWidth] = sourceImage
cv2.imshow('dst', destImage)
cv2.waitKey(0)

但是当我运行脚本时,python解释器显示以下错误:

Traceback (most recent call last):
  File "examples.py", line 30, in <module>
    destImage[yBorder:imgHeight,xBorder:imgWidth] = sourceImage
ValueError: shape mismatch: objects cannot be broadcast to a single shape

出现此错误的原因是什么?怎么解决?

1 个答案:

答案 0 :(得分:1)

试试这个:

destImage[yBorder:yBorder + imgHeight,xBorder:xBorder + imgWidth] = sourceImage

切片语法为start:stop,而不是start:width