Skip to content
Advertisement

How to merge two images in openCv(python)? [closed]

I extracted Red channel at this image

and I created a rectangle for this image

I want to blending as merge this two images and withoutRedChannel is should be positioned inside the rectangle

it is for extract red channel:

 withoutRedChannel=Pozisyonlama[:,:,2]

it is for rectangle:

    img_rect = cv2.rectangle(image, pt1, pt2, recColor, thickness, lineType)   
   
    frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = QImage(frame, frame.shape[1],frame.shape[0],frame.strides[0],QImage.Format_RGB888)
    

my function’s full code here:

  def setRectangleRedChannel(self,_image):
    lineType = cv2.LINE_4
    
    pt1 = (0,45)
    pt2 = (320, 135)
    recColor = (200, 0, 0)
    thickness = 2
    
    x, y = pt1[0], pt1[1]
    w, h = pt2[0] - pt1[0], pt2[1] - pt1[1]
   
    
    image = cv2.resize(_image,(320,180))
    
    Pozisyonlama = image[y:y+h, x:x+w]
    
    
    
    
    
    withoutRedChannel=Pozisyonlama[:,:,2]
    
    cv2.imshow("",withoutRedChannel)
    
  
    
    #dst = cv2.addWeighted(image.img, 1, withoutRedChannel.img, 1, 0.0)

    
    
  
  
    
    
    
    
    
   
   
    
    
    img_rect = cv2.rectangle(image, pt1, pt2, recColor, thickness, lineType)   
   
    frame = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = QImage(frame, frame.shape[1],frame.shape[0],frame.strides[0],QImage.Format_RGB888)
    
    
    self.redChannel_image.setPixmap(QtGui.QPixmap.fromImage(image))

Advertisement

Answer

If you want to merge two images into one, you can do this:

img[y_min:y_max,x_min:x_max] = template

where img is your full image and template is the cropped image. Be sure that both images have the same channels.

If your template image is in gray scale, you have to do this before to merged with the full image:

h, w = template
templateColor = numpy.zeros((h,w,3),numpy.uint8)
for j in range(h):
    for i in range(w):
        templateColor [j,i,:] = template[j,i]

For your code, will be:

def setRectangleRedChannel(_image):
    lineType = cv2.LINE_4
    pt1 = (0,45)
    pt2 = (320, 135)
    recColor = (200, 0, 0)
    thickness = 2
    x, y = pt1[0], pt1[1]
    w, h = pt2[0] - pt1[0], pt2[1] - pt1[1]
    image = cv2.resize(_image,(320,180))
    withoutRedChannel = image[y:y+h, x:x+w,2]
    color = numpy.zeros((h,w,3),numpy.uint8)
    for j in range(h):
        for i in range(w):
            color[j,i,:] = withoutRedChannel[j,i]
    image[y:y+h, x:x+w] = color[:,:,:]
    cv2.imshow("",image)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement