【问题标题】:Filling a blank image with another with opencv用opencv填充另一个空白图像
【发布时间】:2014-11-18 16:20:07
【问题描述】:

我正在使用带有 cv2 库的 python。我有一个小图像,我想在周围填充一些空白区域。假设空白图像如下:(每个x表示一个像素,[255,255,255])

x x x x
x x x x
x x x x
x x x x

我想将它的某些部分交换为另一个图像中的数据(每个 a 表示另一个图像中的一个像素)

x x x x
x a a x
x a a x
x x x x

最快的方法是什么?我尝试循环遍历每个像素并完成这项工作,但它似乎效率非常低。

import cv2
import numpy as np
tmp=np.zeros((1024,768,3),np.uint_8)
image= .. #image captured from camera
for(i in range(480)):
  for(j in range(640)):
    tmp[i+144][j+197]=image[i][j]

【问题讨论】:

  • 在opencv doc中查看感兴趣的区域
  • 感兴趣的区域是哪个?

标签: python opencv


【解决方案1】:

简而言之,您可以这样做:

Size taille = new_image.size();   // New_image is the image to be inserted
Mat  white_roi( white_image, Rect( x, y, taille.width, taille.height ) );
                                  // white_roi is a subimage of white_image
                                  //          that start from the point (x,y)
                                  // and have the same dimension as a new_image
new_image.copyTo( white_roi );    // You copy the new_image into the white_roi,
                                  //          this in the original image

这是c++代码,要适应python。

【讨论】:

  • 谢谢,但是python中不存在Mat类,所以迁移这段代码有点困难
【解决方案2】:

使用 numpy 切片。

tmp = np.zeros((1024,768,3),np.uint_8)

img[y1:y2, x1:x2] = tmp[y3:y4, x3:x4] # given that (y2-y1) = (y4 - y3) and same for x

或者用一些颜色填充它

img[y1:y2, x1:x2] = (255, 255, 255)

【讨论】:

    【解决方案3】:

    如果你想替换一些大的部分,比如矩形,那么使用 ROI 来替换(正如其他答案已经解释过的)。但如果你正在处理随机分布的像素或复杂的形状,那么你可以试试这个。

    1) 为要替换的部分创建一个掩码二值图MaskImage,其余部分设置为false。

    2) Result = MasterImage AND (NOT(MaskImage)) + PickerImage AND MaskImage.

    PS:我没有用过python,因为我不懂Python,而且它很容易表达。祝你好运

    【讨论】:

      【解决方案4】:

      先把图片换成数组再替换。

      试试这个:

      import cv2
      import numpy as np
      tmp=np.zeros((1024,768,3),np.uint_8)
      image= .. #image captured from camera
      src = np.array(image)
      
      tmp[144:, 197:] = src
      

      首先确保元素的数量是正确的。

      【讨论】:

      • 嗯,好像报错了:a=np.zeros((5,5,3),np.uint8) b=np.zeros((3,3,3),np.uint8) a[:,:]=[255,255,255] a[1:,1:]=b #it says:ValueError: operands could not be broadcast together with shapes (4,4,3) (3,3,3)
      猜你喜欢
      • 2012-05-09
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      相关资源
      最近更新 更多