”Python-OpenCV” How to Enlargement Image from Designate Point as Center

Python
higashi
higashi

Hi, I’m higashi.

 

This time I introduce how to enlargement image from designate point as center.

The below movie is the sample.

指定位置を中心に画像を拡大するという作業イメージ動画

I think you can confirm the image is enlarged without the white point is moved.

 

*The sample is movie, but the program introduced later can produce only one image after enlargement.

 

If it is fit to your request, please read continuously.

 

Sponsored Links

Necessary Information for Enlargement

The below information should be designated before.

In () is variables that is used in the program shown later.

1.Base Imge (sample.jpg)

2.Enlargement Ratio to Horizontal (cx)

3.Enlargement Ratio to Vertical (cy)

4.Enlargement Center Point Pixel Number from left (x1)

5.Enlargement Center Point Pixel Number from upper (y1)

 

By using these information, the program introduced later conduct the process.

So please adjust these information to appropriately to match your situation.

 

Sponsored Links

Sample Code of Enlargement Image from Designated Point

This is the sample code of enlargement image from designated point as center.

#import library
import numpy as np
import cv2

#load image and input information
img=cv2.imread('sample.jpg',cv2.IMREAD_GRAYSCALE)
h,w=img.shape[:2]
cx=3
cy=3
x1=230 #pixel
y1=240 #pixel

#describe the center point
#if you don't need, please comment out these two lines.
cv2.circle(img,center=(x1,y1),radius=10,color=255,thickness=-1)
cv2.imwrite('img_point.png',img)

#process of enlargement
x2=x1*cx #pixel
y2=y1*cy #pixel
size_after=(int(w*cx), int(h*cy))
resized_img=cv2.resize(img, dsize=size_after)
deltax=(w/2-x1)-(resized_img.shape[1]/2-x2)
deltay=(h/2-y1)-(resized_img.shape[0]/2-y2)

framey=int(h*cy*2)
framex=int(w*cx*2)
finalimg=np.zeros((framey,framex),np.uint8)
finalimg[int(-deltay+framey/2-resized_img.shape[0]/2):int(-deltay+framey/2+resized_img.shape[0]/2),
         int(-deltax+framex/2-resized_img.shape[1]/2):int(-deltax+framex/2+resized_img.shape[1]/2)]=resized_img
finalimg=finalimg[int(finalimg.shape[0]/2-h/2):int(finalimg.shape[0]/2+h/2),int(finalimg.shape[1]/2-w/2):int(finalimg.shape[1]/2+w/2)]

#output result image
cv2.imwrite('final_img.jpg',finalimg)
higashi
higashi

It is too long program.

 

I thought it would be easy, but when I tried it, it was difficult.

 

This program include the process of describing the center point for enlargement.

If you don’t need it, please delete the 15 and 16 lines.

 

Sponsored Links

Result of Sample Code

Finally, let’s conduct the sample code by changing variables.

Left image is original and right image is after enlargement.

★The Result cx=0.7, cy=0.7

The result of sample code(sample1)

★The Result cx=0.7, cy=1.3

The result of sample code(sample2)

★The Result cx=3.0, cy=3.0

The result of sample code(sample3)

I think all result is no problem.

 

That’s all. Thank you!!

コメント