It looks like a fishing title.
The type of OpenCV is numpy.ndarray. So you can take out a part of it with Slice. Since it is a matrix, the order is row and column. Since it is a matrix, specify "from which row (column) to which row (column)". It is not "upper left coordinates and cut size". The point is img [r1: r2, c1: c2], but if you understand the theory, it's easy to memorize the notation ** img [r: r + h, c: c + w] **.
By the way, when the upper left coordinate is defined as x, y =…, which of h, w =… and w, h =… is more appropriate for writing the size? Elementary School Arithmetic [Multiplication Order Problem](https://ja.wikipedia.org/wiki/%E3%81%8B%E3%81%91%E7%AE%97%E3%81%AE%E9%A0 % 86% E5% BA% 8F% E5% 95% 8F% E9% A1% 8C) has become a hot topic these days, and there is a possibility that this case will become a new fire in the compulsory programming education class. is there.
Of course, trimming can be done with PIL (Pillow), but I won't mention it here because it would be confusing to write the PIL specifications.
trim.py
import cv2
filename = "nurse.jpg "
img = cv2.imread(filename)
x, y = 380, 30
h, w = 160, 120
img_trim = img[y:y+h, x:x+w]
cv2.imshow("origin", img)
cv2.imshow("trim", img_trim)
cv2.imwrite("trimmed_image.jpg ", img_trim)
cv2.waitKey(0)
cv2.destroyAllWindows()
From the original image (Skimanurs) We were able to extract an area of height 160 x width 120 starting from (x, y) = (380,30). Of course, if you include face recognition, you don't have to manually change the position and size.
Use cv2.imwrite (* filename *, * mat *).
This alone is not interesting, so I wrote a program to change the trimming position while turning the loop.
peep.py
import cv2
from PIL import Image
filename = "nurse.jpg "
img = cv2.imread(filename)
imgH, imgW = img.shape[:2]
#As you want
x, y = 50, 100
dx,dy = 2, 3
h, w = 160, 160
imgs=[]
while True:
if 0 <= x+dx <= imgW-w : #You can write like this.
x = x+dx
else:
dx = -dx
if 0 <= y+dy <= imgH-h :
y = y+dy
else:
dy = -dy
window = img[y:y+h, x:x+w]
cv2.imshow("", window)
#See for yourself what happens when you enable this sentence!
# cv2.moveWindow("", x+100, y+100)
imgPIL=Image.fromarray(window[:,:,::-1])
imgs.append(imgPIL)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cv2.destroyAllWindows()
imgs[0].save("peep.gif", save_all=True,
append_images=imgs[1:], optimize=False,
duration=20, loop=0)
This program creates such an animated GIF.
I used to read this kind of game in Bemaga when I called it a peephole, but I've never seen this word used.
When I first touched Excel, I looked at the R1C1 format and said, "R and C, which is the row and which is the column!" "I knew that R was the row and C was the column, but I wrote the xy coordinates as x, y. If the line is RC, the lineup is reversed! ”Remembers being indignant. I didn't think I would go out with that discomfort again.
Recommended Posts