0
1

More than 1 year has passed since last update.

【python】画像を任意の横軸で分割

Posted at
import numpy as np
import cv2

def onMouse(event, x, y, flag, wname):
    global cnt
    global img
    
    if event == cv2.EVENT_MOUSEMOVE:  # when mouse move, draw line
        img2 = np.copy(img)
        h, w = img2.shape[0], img2.shape[1]
        # cv2.line(img2, (x, 0), (x, h - 1), (255, 0, 0), thickness=2) # vertical line
        cv2.line(img2, (0, y), (w - 1, y), (255, 0, 0), thickness=2) # horizontal line
        cv2.imshow(wname, img2)

    if event == cv2.EVENT_LBUTTONDOWN:  # when left click, get (x, y) and split image
        print(x, y)

        # split image
        cv2.imwrite('split_pic/split_' + '{:03d}'.format(cnt) + '.jpg', img[:y, :, :])
        cnt += 1

        # update image
        img = np.copy(img[y:, :, :])
        cv2.imshow(wname, img)

if __name__ == '__main__':
    # global parameter
    cnt = 0
    img = cv2.imread('sample.png')

    wname = 'MouseEvent'
    cv2.namedWindow(wname)
    cv2.setMouseCallback(wname, onMouse, wname)
    cv2.imshow(wname, img)
    cv2.waitKey()
    cv2.destroyAllWindows()

参考
【python-openCV】画像を縦、横方向に指定数で等分割する方法! - ヒガサラblog
Pythonで画像の座標を取得する方法を現役エンジニアが解説【初心者向け】 | TechAcademyマガジン
python — Python OpenCV CV2のimshow()ウィンドウを更新する方法
python — opencvのwaitKey()関数に他のキーを使用する
OpenCVを使ってマウスイベント(手動)でテニスコート領域を選択できるようにする - Qiita
Python, OpenCVで図形描画(線、長方形、円、矢印、文字など) | note.nkmk.me
Python, formatで書式変換(0埋め、指数表記、16進数など) | note.nkmk.me

0
1
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
1