0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

OpenCVを用いる画像の基本的な操作方法

Posted at

#画像をx軸またはy軸に移動させる
■コード

translate.py
import cv2
import numpy as np

#read image
img = cv2.imread("gotg_rocket.jpg")

#shift image to left(negative value) or right(positive value)
tx = 100

#shift image to up(negative value) or down(positive value)
ty = 100

#transformation matrix(need to be float value)
M = np.float32([[1,0,tx],[0,1,ty]])

#width and height of image
h = img.shape[0]
w = img.shape[1]

#translate image
translated = cv2.warpAffine(img,M,(w,h))

#show image
cv2.imshow("Original",img)
cv2.imshow("Translated", translated)
cv2.waitKey(0)

■実行結果
・元の画像
original.png
・変換した画像
translated.png

#画像を回転させる
■コード

rotate.py
import cv2

#read image
img = cv2.imread("gotg_rocket.jpg")

#width and height of image
h = img.shape[0]
w = img.shape[1]

#get center of image
center = (w//2,h//2)

#rotation angle(in degree)
angle = 40

#scale rate(if don't want to change the size  of image, set to 1)
scale = 1.0

#transformation matrix
M = cv2.getRotationMatrix2D(center,angle,scale)

#rotate image
rotated = cv2.warpAffine(img,M,(w,h))

#show image
cv2.imshow("Original",img)
cv2.imshow("Rotated", rotated)
cv2.waitKey(0)

■実行結果
・元の画像
original.png

・変換した画像
rotated.png

#画像のサイズを変更させる
■コード

resize.py
import cv2

#read image
img = cv2.imread("gotg_rocket.jpg")

#resize width
w = 300

#resize height(keeping the scale rate)
h = int(300/img.shape[1]*img.shape[0])

#resize image
resized = cv2.resize(img,(w,h))

#show image
cv2.imshow("Original",img)
cv2.imshow("Resized", resized)
cv2.waitKey(0)

■実行結果
・元の画像
original.png

・変換した画像
resized.png

#画像を反転させる
■コード

flip.py
import cv2

#read image
img = cv2.imread("gotg_rocket.jpg")

#flip image (-1:vertical & horizontal, 0: vertically, 1:horizontal)
flipped = cv2.flip(img,0)

#show image
cv2.imshow("Original",img)
cv2.imshow("Flipped", flipped)
cv2.waitKey(0)

■実行結果
・元の画像
original.png

・変換した画像
flipped.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?