I think you are trying to crop the image and save the cropped portion as a new image. Below is the sample code to do that.

import cv2
import numpy as np

img = cv2.imread(r'.\dump.png', 1)  # '1' read as color image
h,w = img.shape[:2]
print 'image height and width = %d x %d' % (h, w)  # 318 * 348 pixels

img = img[50:250,50:280]  # crop image at [h1:h2, w1:w2]
cv2.imwrite(r'.\dump_resized.png',img)

Here is cropped and saved image.

This is what you intended to do?

UPDATE:

To resize the image and put it as a picuture-in-picture one. You may resize the image first, by 1/10 for instance.

resized_image = cv2.resize(img, (h/8, w/8))
h1, w1 = resized_image.shape[:2]

Then put the resized one into the original image.

#set top left position of the resized image
pip_h = 10
pip_w = 10
img[pip_h:pip_h+h1,pip_w:pip_w+w1] = resized_image  # make it PIP
cv2.imwrite(r'.\dump_pip.png',img)

Here is the resulted PIP image.

Answer from thewaywewere on Stack Overflow
๐ŸŒ
Master Data Science
datahacker.rs โ€บ 012-blending-and-pasting-images-using-opencv
#012 Blending and Pasting Images Using OpenCV - Master Data Science
January 5, 2021 - This operation is called pasting and it is performed using a NumPy reassignment operator. We will simply take the values of the larger image and reassign them to match the smaller image in a particular section of the larger image.
Discussions

overlay a smaller image on a larger image python OpenCv - Stack Overflow
Hi I am creating a program that replaces a face in a image with someone else's face. However, I am stuck on trying to insert the new face into the original, larger image. I have researched ROI and More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Copy and paste region of image in opencv? - Stack Overflow
I'm stuck at this tutorial where a ROI is pasted over another region of same image. Python trows a value error when I try something similar: img = cv2.imread(path, -1) eye = img[349:307, 410:383] ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
December 17, 2016
How to paste an image in opencv python - Stack Overflow
cv2.imread("largerimagepath") cv2.imread("smallerimagepath") ##paste smaller image at some point(x,y) in largerimage More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to paste 2 images of different sizes onto same background using cv2? - Stack Overflow
I would like to paste 2 images of different sizes onto a same background using cv2. I found codes, example below that can only merge equal size images which is a limitation. import cv2 as cv i... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
TechTutorialsX
techtutorialsx.com โ€บ home โ€บ python โ€บ python opencv: copy image
Python OpenCV: Copy image - techtutorialsx
November 29, 2020 - import cv2 image = cv2.imread('C:/Users/N/Desktop/Test.jpg') imageCopy = image.copy() cv2.circle(imageCopy, (100, 100), 30, (255, 0, 0), -1) cv2.imshow('image', image) cv2.imshow('image copy', imageCopy) cv2.waitKey(0) cv2.destroyAllWindows()
Top answer
1 of 9
181

A simple way to achieve what you want:

import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

Update

I suppose you want to take care of the alpha channel too. Here is a quick and dirty way of doing so:

s_img = cv2.imread("smaller_image.png", -1)

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])

2 of 9
28

Using @fireant's idea, I wrote up a function to handle overlays. This works well for any position argument (including negative positions).

def overlay_image_alpha(img, img_overlay, x, y, alpha_mask):
    """Overlay `img_overlay` onto `img` at (x, y) and blend using `alpha_mask`.

    `alpha_mask` must have same HxW as `img_overlay` and values in range [0, 1].
    """
    # Image ranges
    y1, y2 = max(0, y), min(img.shape[0], y + img_overlay.shape[0])
    x1, x2 = max(0, x), min(img.shape[1], x + img_overlay.shape[1])

    # Overlay ranges
    y1o, y2o = max(0, -y), min(img_overlay.shape[0], img.shape[0] - y)
    x1o, x2o = max(0, -x), min(img_overlay.shape[1], img.shape[1] - x)

    # Exit if nothing to do
    if y1 >= y2 or x1 >= x2 or y1o >= y2o or x1o >= x2o:
        return

    # Blend overlay within the determined ranges
    img_crop = img[y1:y2, x1:x2]
    img_overlay_crop = img_overlay[y1o:y2o, x1o:x2o]
    alpha = alpha_mask[y1o:y2o, x1o:x2o, np.newaxis]
    alpha_inv = 1.0 - alpha

    img_crop[:] = alpha * img_overlay_crop + alpha_inv * img_crop

Example usage:

import numpy as np
from PIL import Image

# Prepare inputs
x, y = 50, 0
img = np.array(Image.open("img_large.jpg"))
img_overlay_rgba = np.array(Image.open("img_small.png"))

# Perform blending
alpha_mask = img_overlay_rgba[:, :, 3] / 255.0
img_result = img[:, :, :3].copy()
img_overlay = img_overlay_rgba[:, :, :3]
overlay_image_alpha(img_result, img_overlay, x, y, alpha_mask)

# Save result
Image.fromarray(img_result).save("img_result.jpg")

Result:

If you encounter errors or unusual outputs, please ensure:

  • img should not contain an alpha channel. (e.g. If it is RGBA, convert to RGB first.)
  • img_overlay has the same number of channels as img.
๐ŸŒ
OpenCV Q&A Forum
answers.opencv.org โ€บ question โ€บ 231069 โ€บ inserting-logo-in-an-image
Inserting Logo in an image - OpenCV Q&A Forum
#!/usr/bin/env python35 #OpenCV 4.3.0, Raspberry pi3B/+, 4b/4g/8g, Thonny 3.7.3 #Date: 1st July, 2020 import cv2 import numpy as np img1 = cv2.imread('ralph.jpg') overlay_img1 = np.ones(img1.shape,np.uint8)*255 img2 = cv2.imread('mainlogo.png') rows,cols,channels = img2.shape overlay_img1[450:rows+450, 450:cols+450 ] = img2 img2gray = cv2.cvtColor(overlay_img1,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray,220,55,cv2.THRESH_BINARY_INV) mask_inv = cv2.bitwise_not(mask) temp1 = cv2.bitwise_and(img1,img1,mask = mask_inv) temp2 = cv2.bitwise_and(overlay_img1,overlay_img1, mask = mask) result = cv2.add(temp1,temp2) cv2.imshow("Result",result) cv2.imwrite("Result.jpg",result) cv2.waitKey(0) cv2.destroyAllWindows()
Top answer
1 of 3
6

Your slice [349:307, 410:383] returns an empty array eye, which could not be assigned to an array view of different shape.

E.g.:

In [8]: import cv2
   ...: fn=r'D:\Documents\Desktop\1.jpg'
   ...: img=cv2.imread(fn, -1)
   ...: roi=img[200:400, 200:300]

In [9]: roi.shape
Out[9]: (200, 100, 3)

In [10]: img2=img.copy()

In [11]: img2[:roi.shape[0], :roi.shape[1]]=roi

In [12]: cv2.imshow('img', img)
    ...: cv2.imshow('roi', roi)
    ...: cv2.imshow('img2', img2)
    ...: cv2.waitKey(0)
    ...: cv2.destroyAllWindows()

result:

NOTE that even if roi is not an empty array, assignment with mismatching shapes will raise errors:

In [13]: img2[:100, :100]=roi
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-85de95cf3ded> in <module>()
----> 1 img2[:100, :100]=roi

ValueError: could not broadcast input array from shape (200,100,3) into shape (100,100,3)
2 of 3
3

I would guess that there's something off with your image. Let's look at the error returned

ValueError: could not broadcast input array from shape (0,0,3) into shape (150,165,3)

So eye appears to have the dimension (0,0,3) and img has the dimension (150,165,3). The 3 corresponds to RGB which is the 3 different color channels. So your original image is 150x165. But you tried to select a region at img[349:307, 410:383]. I suspect since the region you specified is outside the image it is not selecting anything hence the dimensions (0,0,3).

Try import pdb; pdb.set_trace() after the second line where you initialize eye. This will pop you into an interactive python terminal where you can see what's going on. Try to see what the dimensions of img are and if it's really what you want. Maybe the image you downloaded is smaller than the example causing the error.

Check out the first answer to a similar question. Your method for getting roi looks correct so try just adjusting the coordinates to a smaller region that fits.

๐ŸŒ
YouTube
youtube.com โ€บ ivan goncharov
Pasting Images into Images with OpenCV | Learn OpenCV in Python by MAKING MEMES #6 - YouTube
Wow, I think it's the coolest video in the series so far! In this one we explore pasting images into frames and frames into images with the stonks guy! Hope ...
Published: May 24, 2020
Views: 341
๐ŸŒ
ProjectPro
projectpro.io โ€บ recipes โ€บ add-two-images-opencv
Cv2.add - Cv2 add - Opencv add two images - Projectpro
February 17, 2023 - The images that we are using for this recipe are as follows. import cv2 import numpy as np image1 = cv2.imread('project.jpg') image2=cv2.imread('OpenCV_Logo.jpg')
Find elsewhere
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63248533 โ€บ how-to-paste-an-image-in-opencv-python
How to paste an image in opencv python - Stack Overflow
image.paste() works only with pillow.Image but cv2 gives you numpy.array so you can do image[row_start:row_end,col_start:col_end] = other_image and you don't have to use [c]
๐ŸŒ
GitHub
gist.github.com โ€บ uchidama โ€บ 41d1c0a068f1d36dec2706715a7f17aa
opencv image paste code. https://stackoverflow.com/questions/14063070/overlay-a-smaller-image-on-a-larger-image-python-opencv ยท GitHub
opencv image paste code. https://stackoverflow.com/questions/14063070/overlay-a-smaller-image-on-a-larger-image-python-opencv - overlay_image_python_opencv.ipynb
๐ŸŒ
Analytics Vidhya
analyticsvidhya.com โ€บ home โ€บ advanced opencv and numpy operations: cropping, copying, and pasting
Advanced OpenCV and NumPy Operations: Cropping, Copying, And Pasting
July 28, 2021 - cv2.imshow('Cropped Trees', image) cv2.waitKey() cv2.destroyAllWindows() Output to the above code block will show as follows: And thus, we have successfully cropped the tree from our image and added more trees to the original image, using a method of Copying And Pasting.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ add-image-to-a-live-camera-feed-using-opencv-python
Add image to a live camera feed using OpenCV-Python - GeeksforGeeks
January 3, 2023 - Next, we should set a space for the image where it is going to be placed in the webcam feed By masking out that area for a smooth placement of the image. For that, we are going to use the cv2.cvtColor (To know more visit cv2.cvtColor ) to first convert the given image into a grayscale image, because it is easy to process the image in OpenCV if the image is in grayscale, and mask out the area by thresholding the pixels in that range by cv2.THRESH_BINARY ( To know more visit cv2.THRESH_BINARY ) to create a space for the image to appear.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 75982819 โ€บ how-to-paste-2-images-of-different-sizes-onto-same-background-using-cv2
python - How to paste 2 images of different sizes onto same background using cv2? - Stack Overflow
Your 512px tall image can't fill a space 522px tall. ... Thank you, I got what you mean. ... import cv2 as cv img_0 = cv.imread("Star.png") img_1 = cv.imread("Triangle.png") bg_img = cv.imread("White.png") bg_img[0:0+img_0.shape[0], 0:0+img_0.shape[1]] = img_0 bg_img[250:250+img_1.shape[0], 250:250+img_1.shape[1]] = img_1 cv.imwrite("bg_img.tiff", bg_img)
๐ŸŒ
GitHub
gist.github.com โ€บ 7007835
OpenCV: paste a image ยท GitHub
OpenCV: paste a image ยท Raw ยท opencv_copyTo.cpp ยท This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-copy-and-paste-images-onto-other-image-using-pillow
Python | Copy and Paste Images onto other Image using Pillow - GeeksforGeeks
January 18, 2022 - # import image module from pillow from PIL import Image # open the image Image1 = Image.open('D:\cat.jpg') # make a copy the image so that the # original image does not get affected Image1copy = Image1.copy() Image2 = Image.open('D:\core.jpg') Image2copy = Image2.copy() # paste image giving dimensions Image1copy.paste(Image2copy, (0, 0)) # save the image Image1copy.save('D:\pasted2.png')
๐ŸŒ
Learning About Electronics
learningaboutelectronics.com โ€บ Articles โ€บ How-to-make-a-copy-of-an-image-Python-numpy.php
How to Make a Copy of an Image in Python using the Numpy Module
After this, we read in the image using the cv2.imread() function. If the image is located in the current working directory, then you simply specify the file name. If the image is not located in the current working directory, then you must specify the path to the file.
๐ŸŒ
YouTube
youtube.com โ€บ edusoft knowledgeverse
How to Copy-Paste an image using OpenCV. - YouTube
How to Copy-Paste an image using OpenCV. #shortsvideo#shorts #short #shortvideo #shortsvideo #python #pythonlearning #pythonprogramming #pythontutorial #pyth...
Published: September 2, 2023
Views: 187
๐ŸŒ
Topcoder
topcoder.com โ€บ thrive โ€บ articles โ€บ python-for-image-recognition-opencv
Python for Image Recognition - OpenCV
December 11, 2020 - It is used for machine learning, computer vision and image processing. You can extract the most out of OpenCV when integrated with powerful libraries like Numpy and Pandas. Open Terminal/Command Prompt and type : ~ pip install opencv-python ยท 1.Open PyCharm. 2.Import cv2. 3.Paste a test image in the directory.
๐ŸŒ
OpenCV
forum.opencv.org โ€บ python
Paste video on the top of the image - Python - OpenCV
September 17, 2022 - Hi, i am new in open cv tool. I hope you guys help to fix this issue . My concept is paste video on the top of the image. I mean the image will be backward and the video will be forward! bgrm_image(this is the image which i want to use as a background of the video ) nparr = np.fromstring(bgrm_image, np.uint8) bgrm_Img = cv2.imdecode(nparr, cv2.IMREAD_UNCHANGED) vid = cv2.VideoCapture("transperent.mov") ret, frame = vid.read() try: while(ret): ret, frame = vid.read() ...