@j0083

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

画像拡大プログラムを言語化してほしい

プログラムを言語化してほしい

python 初心者です
下にあるコードは,指定した位置を中心に画像を拡大することができるコードらしいのですが,
なぜ拡大してるのに変換された画像のサイズが変わっていないのかが理解できません.
このプログラムがどのようにして拡大されているか言語化できる方いましたら,していただけますでしょうか?

また,拡大してるのにサイズが変わらないとなると穴?(情報が不足している画素?)ができてしまうことを想像しているのですが,この点に関しましても分かる方いましたら説明していただけると幸いです。説明へたで,すみません.

拡大画像データ(sample.jpg)
横方向の拡大率(cx)
横方向の拡大率(cy)
拡大する際の横方向基準位置(x1)
拡大する際の縦方向基準位置(y1)

指定した位置を中心に画像を拡大するプログラム

import numpy as np
import cv2

#ベース画像の読み込み&情報入力
img=cv2.imread('sample.jpg',cv2.IMREAD_GRAYSCALE)
h,w=img.shape[:2]
cx=3
cy=3
x1=230 #pixel
y1=240 #pixel

#画像の拡大作業開始
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)]

#結果の出力
cv2.imwrite('final_img.jpg',finalimg
0 likes

1Answer

以下のような処理を行っているかと思われます。

入力画像のサイズを$(w,h)$、基準点を$(x_1,y_1)$とすると、

  1. 入力画像を$(c_x,c_y)$倍した画像A(resized_img)を作成する。サイズは$(c_x w, c_y h)$となる。
  2. さらに2倍した(つまりサイズが$(2 c_x w, 2 c_y h)$の)真っ黒な画像B(finalimg)を作成する。この画像Bに、上で作成した画像Aを(拡大縮小せず等倍で)中央付近(位置については後述)に張り付ける。
  3. 画像Bの中心、$(c_x w - w/2, c_y h - h/2)-(c_x w + w/2, c_y h + h/2)$の矩形領域を切り取って出力画像とする(最後のfinalimgへの代入)。サイズは$(w, h)$となる。

上記2での画像の貼り付けは、最終的な出力画像の中心$(w/2, h/2)$に、入力画像の$(x_1-(x_1-w/2)/c_x, y_1 - (y_1 - h/2)/c_y)$が来るように貼り付けています(なぜこの点を選んでいるのかはよくわかりません)。

もし$(x_1,y_1)$が出力画像の中央に来るようにしたいのなら、

deltax = - cx * (w/2 - x1)
deltay = - cy * (h/2 - y1)

とするとよいです。

0Like

Your answer might help someone💌