Macroの杜( Python編 )
[ Python for LibreOffice ]

【 追加Library 】


**********************【 Index 】**********************

【 追加Library 】

Libraryの追加はIDE参照



OpenCV

[ 動画 ]



Pygame



Pyautogui




pywin32( Windows APIも参照 )

[ FileSystemObject ]

[ WScript.Network ]

[ win32gui ]

[ win32api ]



pythonnet




******************************[ Macro Code ]******************************


【追加ライブラリー 】

OpenCV

OpnCv-)[General]画像を読込/表示/保存


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 入力画像を読込
		img = cv2.imread('C:/Temp/test01.png')	#ファイル名は半角英数
		#
		# 画像の表示
		cv2.imshow('image',img)
		#
		# キーボード入力
		cv2.waitKey(0)
		# 現在までに作られた全てのウィンドウを閉じる
		cv2.destroyAllWindows()
		#
		# 画像の書込
		cv2.imwrite('C:/Temp/write.png', img)
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# パプリカの画像はfood.foto(フード ドット フォト)の画像を利用させて頂きました。

OpnCv-)[General]縮小/拡大


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 入力画像を読込
		img = cv2.imread('C:/Temp/test01.png')	#ファイル名は半角英数
		#
		# 画像サイズの取得
		height = img.shape[0]
		width = img.shape[1]
		# 横*1、縦*0.5 に変更
		img2 = cv2.resize(img , (int(width*1), int(height*0.5)), interpolation =  cv2.INTER_AREA)
		#
		# 画像の表示
		cv2.imshow('LO6.4.2.3(x64)',img2)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# interpolation(補間方法)は省略可能で、以下がある。デフォルトの補間方法は cv2.INTER_LINEAR。
# 但し、省略した場合、resize後、色が変化する場合もある。
# 縮小には cv2.INTER_AREA
# 拡大には cv2.INTER_CUBIC (処理が遅い)又はcv2.INTER_LINEAR(早い)
# が適している。
#
# INTER_LINEAR 	bilinear(双線型) interpolation
# INTER_NEAREST 	nearest neighbor(近傍) interpolation
# INTER_CUBIC 	bicubic(バイキュービック) interpolation
# INTER_AREA 	resampling using pixel area relation
# INTER_LANCZOS4 	Lanczos interpolation over 8x8 neighborhood

OpnCv-)[General]並進


#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/test01.png')
		# 形状を取得する為グレースケール変換。Colorのままではエラー
		temp = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
		# 形状取得
		rows, cols = temp.shape
		#
		M = np.float32([[1,0,100],[0,1,50]])
		dst = cv2.warpAffine(img,M,(cols,rows))
		oShow('warpAffine', dst)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

OpnCv-)[General]回転


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/test01.png')
		# 形状を取得する為グレースケール変換
		temp = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
		# 形状取得
		rows, cols = temp.shape
		#
		M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)
		dst = cv2.warpAffine(img,M,(cols,rows))
		oShow('getRotationMatrix2D', dst)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

OpnCv-)[General]アフィン変換

#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/test01.png')
		# 線を追加
		oColor = (255, 255, 255)	#white = (Blue, Green, Red)
		oThick = 2	#文字の太さ
		pts = np.array(((10, 100), (300, 100)))
		cv2.polylines(img, [pts], True, oColor, oThick)
		pts1 = np.array(((10, 150), (300, 150)))
		cv2.polylines(img, [pts1], True, oColor, oThick)
		pts2 = np.array(((10, 200), (300, 200)))
		cv2.polylines(img, [pts2], True, oColor, oThick)
		pts3 = np.array(((10, 250), (300, 250)))
		cv2.polylines(img, [pts3], True, oColor, oThick)
		pts4 = np.array(((50, 50), (50, 250)))
		cv2.polylines(img, [pts4], True, oColor, oThick)
		pts5 = np.array(((100, 50), (100, 250)))
		cv2.polylines(img, [pts5], True, oColor, oThick)
		pts6 = np.array(((150, 50), (150, 250)))
		cv2.polylines(img, [pts6], True, oColor, oThick)
		pts7 = np.array(((200, 50), (200, 250)))
		cv2.polylines(img, [pts7], True, oColor, oThick)
		oShow('warpAffine', img)
		#
		# 形状を取得する為グレースケール変換
		temp = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
		# 形状取得
		rows,cols = temp.shape
		pts1 = np.float32([[50,50],[200,50],[50,200]])
		pts2 = np.float32([[10,100],[200,50],[100,250]])
		#
		M = cv2.getAffineTransform(pts1,pts2)
		dst = cv2.warpAffine(img,M,(cols,rows))
		#
		oShow('warpAffine', dst)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')



OpnCv-)[General]射影変換

#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/shougi.png')
		# 線を追加
		oColor = (255, 0, 0)	#(Blue, Green, Red)
		oThick = 3	#文字の太さ
		pts = np.array(((93, 23), (20,130), (212, 160), (230,32)))
		cv2.polylines(img, [pts], True, oColor, oThick)
		oShow('warpPerspective', img)
		#
		# 形状を取得する為グレースケール変換
		temp = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
		# 形状取得
		rows,cols,ch = img.shape
		pts1 = np.float32([[93,23],[20,130],[212,160],[230,32]])
		pts2 = np.float32([[50,50],[50,250],[250,250],[250,50]])
		#
		M = cv2.getPerspectiveTransform(pts1,pts2)
		#
		dst = cv2.warpPerspective(img,M,(300,300))
		#
		oShow('warpPerspective', dst)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')


将棋盤の画像はPotockより

OpnCv-)[General]画像に文字追加


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 入力画像を読込
		img = cv2.imread('C:/Temp/test01.png')	#ファイル名は半角英数
		#
		oTxt = 'Paprika'
		oPos = (5, 50)	#文字の左下の位置(x,y)
		oFont = cv2.FONT_HERSHEY_PLAIN
		oSize = 4	#フォントサイズ
		oColor = (255, 255, 255)	#white = (Blue, Green, Red)
		oBold = 5		#文字の太さ
		oLineType = cv2.LINE_AA		# cv2.LINE_AAが奨励
		#
		cv2.putText(img, oTxt, oPos, oFont, oSize, oColor, oBold, oLineType)
		#
		# 画像の表示
		cv2.imshow('LO6.4.3.2(x64)',img)
		#
		# キーボード入力
		cv2.waitKey(0)
		# 現在までに作られた全てのウィンドウを閉じる
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# 【 Font
# CV_FONT_HERSHEY_SIMPLEX, CV_FONT_HERSHEY_PLAIN, CV_FONT_HERSHEY_DUPLEX, CV_FONT_HERSHEY_COMPLEX, CV_FONT_HERSHEY_TRIPLEX, CV_FONT_HERSHEY_COMPLEX_SMALL, CV_FONT_HERSHEY_SCRIPT_SIMPLEX, CV_FONT_HERSHEY_SCRIPT_COMPLEX

OpnCv-)[General]画像に図形(多角形)追加


#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 入力画像を読込
		img = cv2.imread('C:/Temp/test01.png')	#ファイル名は半角英数
		#
		oColor = (255, 255, 255)	#white = (Blue, Green, Red)
		oThick = 5	#文字の太さ
		#
		pts = np.array(((80, 130), (65, 150), (80, 180), (110,180), (125,150), (110,130)))	#多角形のポイントの座標
		cv2.polylines(img, [pts], True, oColor, oThick)
		#
		# 画像の表示
		cv2.imshow('LO6.4.3.2(x64)',img)
		#
		# キーボード入力
		cv2.waitKey(0)
		# 現在までに作られた全てのウィンドウを閉じる
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# 多角形以外はnote.nkmk.me参照

OpnCv-)[General]マウスクリックで円を追加描写


#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
# 描写フレームの作成←注:メインルーチンに入れると追加描写されない
img = np.zeros((600,600,3), np.uint8)
cv2.namedWindow(winname='mouse_drawing')
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def draw_circle(event,x,y,flags,param):
	#
	if event == cv2.EVENT_LBUTTONDOWN:	# マウスの左クリックのイベント
		cv2.circle(img,(x,y),100,(0,255,0),-1)
	elif event == cv2.EVENT_RBUTTONDOWN:    # マウスの右クリックのイベント
		cv2.circle(img,(x,y),100,(0,0,255),-1)
    	#
def oTest():
	try:
		cv2.setMouseCallback('mouse_drawing',draw_circle)
		while True:
			cv2.imshow('mouse_drawing',img)
			if cv2.waitKey(20) & 0xFF == 27:	# ESCを押したら画面を閉じる
				break
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# マウスイベントは画像情報処理研究室参照

OpnCv-)[General]カラーパレットとしてのトラックバー


#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def nothing(x):
	pass
#
def oTest():
	try:
		# Create a black image, a window
		img2 = np.zeros((180,300,3), np.uint8)
		#
		cv2.namedWindow('Color Picker')
		#
		# create trackbars for color change
		cv2.createTrackbar('R','Color Picker',0,255,nothing)
		cv2.createTrackbar('G','Color Picker',0,255,nothing)
		cv2.createTrackbar('B','Color Picker',0,255,nothing)
		#
		# create switch for ON/OFF functionality
		switch = '0 : OFF \n1 : ON'
		cv2.createTrackbar(switch, 'Color Picker',0,1,nothing)
		#
		while(1):
			cv2.imshow('image2',img2)
			k = cv2.waitKey(1) & 0xFF
			if k == 27:
				break
			# get current positions of four trackbars
			r = cv2.getTrackbarPos('R','Color Picker')
			g = cv2.getTrackbarPos('G','Color Picker')
			b = cv2.getTrackbarPos('B','Color Picker')
			s = cv2.getTrackbarPos(switch,'Color Picker')
			#
			if s == 0:
				img2[:] = 0
			else:
				img2[:] = [b,g,r]
				#
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

OpnCv-)[General]ROI(Region of Interest)


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		img = cv2.imread('C:/Temp/test01.png')
		area = img[80:130, 130:230]	#[y:y, x:x]
		img[180:230, 130:230] = area
		#
		cv2.imshow('image',img)
		#
		# キーボード入力
		cv2.waitKey(0)
		# 現在までに作られた全てのウィンドウを閉じる
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

OpnCv-)[General]画像の色成分の分割と統合

#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		img = cv2.imread('C:/Temp/test01.png')
		#色成分を分割
		b,g,r = cv2.split(img)
		# Blue成分を0
		img[:,:,0] = 0
		cv2.imshow('Blue=0',img)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		# 元の色成分に戻し、Green成分を0
		img = cv2.merge((b,g,r))
		img[:,:,1] = 0
		cv2.imshow('Green=0',img)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		# 元の色成分に戻し、Red成分を0
		img = cv2.merge((b,g,r))
		img[:,:,2] = 0
		cv2.imshow('Red=0',img)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# 色成分の説明は右記サイトが詳しい⇒teratail



OpnCv-)[General]画像の境界領域を作る


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
#
def oTest():
	try:
		img = cv2.imread('C:/Temp/test01.png')
		area = img[80:130, 130:230]	#[y:y, x:x]
		#
		# 境界に線を追加 (対象画像,境界の各方向に対する線幅top, bottom, left, right,borderType,value)
		constant = cv2.copyMakeBorder(area,5,15,10,20,cv2.BORDER_CONSTANT,value=[255,0,0])
		# 
		# 範囲を張り付け
		img[180-5:230+15, 130-10:230+20] = constant	#線太さ分、貼付け範囲を大きくすること
		#
		cv2.imshow('image',img)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

OpnCv-)[General]画像のブレンド

#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 入力画像を読込 注:重ねるsrcのサイズは同じこと
		img1 = cv2.imread('C:/Temp/test03.png')
		img2 = cv2.imread('C:/Temp/test02.png')
		#
		dst = cv2.addWeighted(img1,0.7,img2,0.3,0)
		#
		cv2.imshow('img1',img1)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		cv2.imshow('img2',img2)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		cv2.imshow('dst',dst)
		cv2.waitKey(0)
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')



OpnCv-)[General]ビット単位での処理

#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img1 = cv2.imread('C:/Temp/test01.png')
		img2 = cv2.imread('C:/Temp/OpenCV.png')
		oShow('img2',img2)
		# I want to put logo on top-left corner, So I create a ROI
		rows,cols,channels = img2.shape
		roi = img1[0:rows, 0:cols ]
		oShow('roi',roi)
		#
		# Now create a mask of logo and create its inverse mask also
		img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
		oShow('img2gray',img2gray)
		ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
		mask_inv = cv2.bitwise_not(mask)
		oShow('mask_inv',mask_inv)
		#
		# Now black-out the area of logo in ROI
		img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
		oShow('img1_bg',img1_bg)
		#
		# Take only region of logo from logo image.
		img2_fg = cv2.bitwise_and(img2,img2,mask = mask)
		oShow('img2_fg',img2_fg)
		#
		# Put logo in ROI and modify the main image
		dst = cv2.add(img1_bg,img2_fg)
		oShow('dst',dst)
		img1[0:rows, 0:cols ] = dst
		oShow('img1',img1)
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')



OpnCv-)[General]RGBでの色抽出方法


#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/OpenCV.png')
		#
		# BGRでの色抽出
		bgrLower = np.array([0,0,0])    # 抽出する色の下限(BGR)
		bgrUpper = np.array([0,0,255])    # 抽出する色の上限(BGR)
		img_mask = cv2.inRange(img, bgrLower, bgrUpper) # BGRからマスクを作成
		result = cv2.bitwise_and(img, img, mask=img_mask) # 元画像とマスクを合成
		#
		oShow('Pick Up Color', result)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

OpnCv-)[General]HSVでの色抽出方法


#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/OpenCV.png')
		#
		# 画像をHSVに変換
		hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
		#
		# HSVでの色抽出/Red
		hsvLower = np.array([0,0,0])    # 抽出する色の下限(HSV)
		hsvUpper = np.array([0,255,255])    # 抽出する色の上限(HSV)
		hsv_mask = cv2.inRange(hsv, hsvLower, hsvUpper)    # HSVからマスクを作成
		result = cv2.bitwise_and(img, img, mask=hsv_mask) # 元画像とマスクを合成
		oShow('HSV: Red', result)
		#
		# HSVでの色抽出/Green
		hsvLower = np.array([60,0,0])    # 抽出する色の下限(HSV)
		hsvUpper = np.array([60,255,255])    # 抽出する色の上限(HSV)
		hsv_mask = cv2.inRange(hsv, hsvLower, hsvUpper)    # HSVからマスクを作成
		result = cv2.bitwise_and(img, img, mask=hsv_mask) # 元画像とマスクを合成
		oShow('HSV: Green', result)
		#
		# HSVでの色抽出/Blue
		hsvLower = np.array([120,0,0])    # 抽出する色の下限(HSV)
		hsvUpper = np.array([120,255,255])    # 抽出する色の上限(HSV)
		hsv_mask = cv2.inRange(hsv, hsvLower, hsvUpper)    # HSVからマスクを作成
		result = cv2.bitwise_and(img, img, mask=hsv_mask) # 元画像とマスクを合成
		oShow('HSV: Blue', result)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# RGBとHSV・HSBの相互変換ツールと変換計算式
# HSVの説明はソースに絡まるエスカルゴ / 【python/OpenCV】画像の特定の色を抽出する方法参照 #名称 値の範囲 #色相(H)= 0~180 : 本来は0~360だがOpenCVでは1/2の範囲になる #彩度(S)= 0~255 : 値が0に近づくほど白く、255に近づくほどHの色になる #明度(V)= 0~255 : 値が0に近づくほど黒く、255に近づくほどHの色になる

OpnCv-)[General]単純なしきい値処理

#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/Color.png',0)
		#
		ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
		ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
		ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
		ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
		ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)
		#
		titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
		images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
		#
		for i in range(6):
			oShow(titles[i], images[i])
			#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')



OpnCv-)[General]適応的しきい値処理

#!
#coding: utf-8
# python Marco
import numpy as np
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oShow(arg2, arg1):
	cv2.imshow(arg2,arg1)
	cv2.waitKey(0)
	cv2.destroyAllWindows()
def oTest():
	try:
		# Load two images
		img = cv2.imread('C:/Temp/10a_addWeighted03a.png',0)
		#
		img = cv2.medianBlur(img,5)
		#
		blocksize = 11	# しきい値計算に使用する近傍領域のサイズ.1より大きい奇数を指定
		c = 2			# 計算されたしきい値から引く定数
		#
		ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
		th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,blocksize, c)
		th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,blocksize, c)
		th4 = cv2.adaptiveThreshold(th3,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,blocksize, c)
		#
		titles = ['Original Image', 'Global Thresholding (v = 127)','Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
		images = [img, th1, th2, th3]
		#
		for i in range(4):
			oShow(titles[i], images[i])
			#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')



OpnCv-)[General]





OpnCv-01)[General]テンプレートマッチング

下記CodeはLibreOffice6.2.4.2 (x64)のPyhonマクロで動作するかの確認用に以下のサイトの方法①のCodeを移植(コピー)したものです。
Code引用元 : 西住工房/【Python/OpenCV】テンプレートマッチングの実装(SSD、SAD、NCC、ZNCC)

事前に以下のライブリーを追加しておくこと!
 ・opencv-python
 ・numpy
 
#!
#coding: utf-8
# python Marco
import cv2
import numpy as np
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 入力画像とテンプレート画像をで取得
		img = cv2.imread('C:/Temp/img.png')
		temp = cv2.imread('C:/Temp/temp.png')
		#
		# グレースケール変換
		gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
		temp = cv2.cvtColor(temp, cv2.COLOR_RGB2GRAY)
		#
		# テンプレート画像の高さ・幅
		h, w = temp.shape
		#
		# テンプレートマッチング(OpenCVで実装)
		match = cv2.matchTemplate(gray, temp, cv2.TM_SQDIFF)
		min_value, max_value, min_pt, max_pt = cv2.minMaxLoc(match)
		pt = min_pt
		#
		# テンプレートマッチングの結果を出力
		cv2.rectangle(img, (pt[0], pt[1]), (pt[0] + w, pt[1] + h), (0, 0, 200), 3)
		cv2.imwrite('C:/Temp/write.png', img)
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.2.4.2(x64)')

#Note
# h, w = temp.shape は h = temp.shape[0] / w = temp.shape[1] と同じ。(参考URL: a,b=hogeというような代入される値が二つあるものの意味)

元画像:img.png


比較画像:temp.png
出力結果:write.png

OpnCv-)[General]





[ 動画 ]

Video-)[General]ファイルから動画を読み込む


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 動画を読込
		cap = cv2.VideoCapture('C:/Temp/nhkFireWork.mp4')	#ファイル名は英数のみ。記号も不可
		#
		# 動画終了まで繰り返し
		while(cap.isOpened()):
			# フレームを取得
			ret, frame = cap.read()
			if not ret:
				break
			# フレームを表示
			cv2.imshow('LO6.4.3.2(x64)',frame)
			# qキーが押されたら途中終了
			if cv2.waitKey(25) & 0xFF == ord('q'):
				break
		# 
		cap.release()
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
#  映像:NHKクリエイティブ・ライブラリー
#  cv2.waitKey() に適切な時間を設定。 通常は25ミリ秒。値が小さいと高速に再生。大きいとスロー再生。
#  映像が終了したらLoopを抜けないとエラー ⇒ teratail / 動画再生後,必ずエラーが発生します


Video-)[General]上下反転動画の保存


#!
#coding: utf-8
# python Marco
import cv2
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
def oTest():
	try:
		# 動画を読込
		cap = cv2.VideoCapture('C:/Temp/nhkFireWork.mp4')	#ファイル名は英数のみ。記号も不可
		#
		# 動画情報の取得
		fps    = cap.get(cv2.CAP_PROP_FPS)
		height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
		width  = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
		#
		# 出力先の設定
		fourcc = cv2.VideoWriter_fourcc('M','P','4','V')
		out = cv2.VideoWriter('C:/Temp/output.mp4', int(fourcc), fps, (int(width), int(height)))
		#
		# 動画終了まで繰り返し
		while(cap.isOpened()):
			# フレームを取得
			ret, frame = cap.read()
			if not ret:
				break
			#
			#frameを左右反転
			frame = cv2.flip(frame,0)
			#
			#output.aviにframe毎書込み
			out.write(frame)
			#
			# フレームを表示
			cv2.imshow('LO6.4.3.2(x64)',frame)
			# qキーが押されたら途中終了
			if cv2.waitKey(25) & 0xFF == ord('q'):
				break
		# 
		cap.release()
		out.release()	#書込み開放
		cv2.destroyAllWindows()
		#
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# 動画ファイル再生可否状況 ⇒ Qiita / OpenCVで遊んでみた


Video-)[General]





Pygame

Pygame-)[General]重ねた画像(ボール)を動かす



#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		pygame.init()                                  	# Pygameの初期化
		(w, h) = (400, 280)
		(x, y) = (w/2, h/2)
		screen = pygame.display.set_mode((w, h))    # 大きさ400*300の画面を生成
		pygame.display.set_caption('pygame')              # タイトルバーに表示する文字
		bg = pygame.image.load('C:/Temp/test01.png').convert_alpha() # 背景画像の指定
		rect_bg = bg.get_rect()
		player = pygame.image.load('C:/Temp/basketball_a12.png').convert_alpha() 		# ボール画像の指定
		rect_player = player.get_rect()
		rect_player.center = (x, y) # ボール座標
		#
		while (1):
			screen.blit(bg, rect_bg)	# 背景画像の描画
			screen.blit(player, rect_player) # キャラの描画
			pygame.time.wait(10)		# 更新間隔
			pygame.display.update()     # 画面を更新
			x += 1 						# 画面更新毎にx座標を+1
			y += 1 						# 画面更新毎にy座標を+1
			rect_player.center = (x, y)
			if x > w: 					# 端まで来たら座標を0にリセット
				x = 0
			if y > h: 					# 同上
				y = 0
			# イベント処理
			for event in pygame.event.get():
				if event.type == QUIT:  # 閉じるボタンが押されたら終了
					pygame.quit()       # Pygameの終了(画面閉じられる)
					oDisp = 'Success'
					sys.exit()
				if event.type == KEYDOWN:
					if event.key == K_ESCAPE:
						pygame.quit()
						oDisp = 'Success'
						sys.exit()					
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

Pygame-)[General]文字列(テキスト)の表示


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		pygame.init()                                   # Pygameの初期化
		screen = pygame.display.set_mode((300, 200))    # 大きさ300*200の画面を生成
		pygame.display.set_caption('Pygame')            # タイトルバーに表示する文字
		font = pygame.font.Font(None, 55)               # フォントの設定(55px)
		#
		while (1):
			screen.fill((0,100,0))      # 画面を緑色に塗りつぶし
			text = font.render('LO6.4.3.2(x64)', True, (255,255,255)) 	# 描画する文字列の設定
			screen.blit(text, [20, 100])								# 文字列の表示位置
			pygame.display.update()     								# 画面を更新
			# イベント処理
			for event in pygame.event.get():
				if event.type == QUIT:  # 閉じるボタンが押されたら終了
					pygame.quit()       # Pygameの終了(画面閉じられる)
					oDisp = 'Success'
					sys.exit()					
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

Pygame-)[General]図形描写


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		pygame.init()                                   # Pygameの初期化
		screen = pygame.display.set_mode((400, 250))    # 大きさ600*500の画面を生成
		pygame.display.set_caption('Pygame')            # タイトルバーに表示する文字
		bg = pygame.image.load('C:/Temp/test01.png').convert_alpha() # 背景画像の指定
		rect_bg = bg.get_rect()
		#
		while (1):
			screen.blit(bg, rect_bg)	# 背景画像の描画
			#
			# (100,0)から(280,80)まで線幅5pxで赤色(R=255, G=0, B=0)の直線を描く
			pygame.draw.line(screen, (255,0,0), (100,0), (280,80), 5)   # 直線の描画
			#
			# 左上座標(10,10)、幅80px、高さ50pxの長方形を線幅5pxの緑色(R=0, G=80, B=0),で(R=0, G=160, B=0)描く
			pygame.draw.rect(screen,(0,80,0),Rect(10,10,80,50),5)   # 四角形を描画(塗りつぶしなし)
			pygame.draw.rect(screen,(0,160,0),Rect(30,30,80,50))    # 四角形を描画(塗りつぶし)
			#
			# 左上の座標が(50,50)、幅が150、高さが50の矩形に内接する楕円を線幅5pxの青色(R=0, G=0, B=255),(R=0, G=0, B=200)で描く
			pygame.draw.ellipse(screen,(0,0,255),(50,50,200,100),5) # 楕円を描画(塗りつぶしなし)
			pygame.draw.ellipse(screen,(0,0,200),(300,10,100,100))     # 円を描画(塗りつぶし)
			#
			pygame.display.update()     # 画面を更新
			# イベント処理
			for event in pygame.event.get():
				if event.type == QUIT:  # 閉じるボタンが押されたら終了
					pygame.quit()       # Pygameの終了(画面閉じられる)
					oDisp = 'Success'
					sys.exit()					
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
#
# draw - Pygameドキュメント 日本語訳

Pygame-)[General]矢印キーで円を動かす


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		(w,h) = (300,200)   # 画面サイズ
		(x,y) = (w/2, h/2)
		pygame.init()       # pygame初期化
		screen = pygame.display.set_mode((w, h))    # 大きさ400*400の画面を生成
		pygame.display.set_caption(u'図形の描画')   # タイトルバーに表示する文字
		dif = 10		# 矢印で動く増分値
		#
		while (1):
			pygame.display.update()     # 画面更新
			pygame.time.wait(30)        # 更新時間間隔
			screen.fill((0, 255, 255, 0))  # 画面の背景色
			# 円の中心座標が画面の範囲外にある場合
			if x < 0:
				x = 0
			if x > w:
				x = w
			if y < 0:
				y = 0
			if y > h:
				y = h
			# 円を描画
			pygame.draw.circle(screen, (255,0,0), (int(x), int(y)), 10)
			# イベント処理
			for event in pygame.event.get():
				# 画面の閉じるボタンを押したとき
				if event.type == QUIT:
					pygame.quit()
					oDisp = 'Success'
					sys.exit()
				# キーを押したとき
				if event.type == KEYDOWN:
					# ESCキーなら終了
					if event.key == K_ESCAPE:
						pygame.quit()
						oDisp = 'Success'
						sys.exit()
					# 矢印キーなら円の中心座標を矢印の方向に移動
					if event.key == K_LEFT:
						x -= dif
					if event.key == K_RIGHT:
						x += dif
					if event.key == K_UP:
						y -= dif
					if event.key == K_DOWN:
						y += dif				
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

Pygame-)[General]矢印キー長押し


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		(w,h) = (300,200)   # 画面サイズ
		(x,y) = (w/2, h/2)
		pygame.init()       # pygame初期化
		screen = pygame.display.set_mode((w, h))    # 大きさ300*200の画面を生成
		pygame.display.set_caption(u'Key長押し')   # タイトルバーに表示する文字
		dif = 1		# 矢印で動く増分値
		#
		player = pygame.image.load('C:/Temp/basketball_a12.png').convert_alpha() 		# ボール画像の指定
		rect_player = player.get_rect()
		#
		while (1):
			# キーイベント処理(キャラクタ画像の移動)
			pressed_key = pygame.key.get_pressed()
			if pressed_key[K_LEFT]:
				x-=dif
			if pressed_key[K_RIGHT]:
				x+=dif
			if pressed_key[K_UP]:
				y-=dif
			if pressed_key[K_DOWN]:
				y+=dif
			screen.fill((150, 250, 150, 0))  # 画面の背景色
			screen.blit(player, rect_player) # キャラの描画
			pygame.display.update()     # 画面更新
			pygame.time.wait(30)        # 更新時間間隔
			# 円の中心座標が画面の範囲外にある場合
			if x < 0:
				x = 0
			if x > w:
				x = w
			if y < 0:
				y = 0
			if y > h:
				y = h
			#
			rect_player.center = (x, y) # ボール座標
			# イベント処理
			for event in pygame.event.get():
				# 画面の閉じるボタンを押したとき
				if event.type == QUIT:
					pygame.quit()
					oDisp = 'Success'
					sys.exit()
				# キーを押したとき
				if event.type == KEYDOWN:
					# ESCキーなら終了
					if event.key == K_ESCAPE:
						pygame.quit()
						oDisp = 'Success'
						sys.exit()			
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

Pygame-)[General]マウスクリックで画像(ボール)移動


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		(w,h) = (400,300)   # 画面サイズ
		(x,y) = (w/2, h/2)
		pygame.init()       # pygame初期化
		screen = pygame.display.set_mode((w, h))    # 大きさ300*200の画面を生成
		pygame.display.set_caption(u'マウスクリックでキャラクター移動')   # タイトルバーに表示する文字
		#
		player = pygame.image.load('C:/Temp/basketball_a12.png').convert_alpha() 		# ボール画像の指定
		#
		while (1):
			screen.fill((200, 200, 250, 0))  # 画面の背景色
			screen.blit(player, (x, y)) # キャラの描画
			pygame.display.update()     # 画面更新
			pygame.time.wait(30)        # 更新時間間隔
			#
			for event in pygame.event.get():
				# マウスクリックで画像移動
				if event.type == MOUSEBUTTONDOWN and event.button == 1:
					x, y = event.pos
					x -= player.get_width() / 2
					y -= player.get_height() / 2
            		#
            	# 画面の閉じるボタンを押したとき
				if event.type == QUIT:
					pygame.quit()
					oDisp = 'Success'
					sys.exit()
				# キーを押したとき
				if event.type == KEYDOWN:
					# ESCキーなら終了
					if event.key == K_ESCAPE:
						pygame.quit()
						oDisp = 'Success'
						sys.exit()			
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')

Pygame-)[General]マウスクリックとドラッグで画像(ボール)移動


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		(w,h) = (400,300)   # 画面サイズ
		(x,y) = (w/2, h/2)
		pygame.init()       # pygame初期化
		screen = pygame.display.set_mode((w, h))    # 大きさ300*200の画面を生成
		pygame.display.set_caption(u'マウスクリック & ドラッグでボール移動')   # タイトルバーに表示する文字
		#
		player = pygame.image.load('C:/Temp/basketball_a12.png').convert_alpha() 		# ボール画像の指定
		#
		while (1):
			screen.fill((200, 200, 200, 0))  # 画面の背景色
			screen.blit(player, (x, y)) # キャラの描画
			pygame.display.update()     # 画面更新
			pygame.time.wait(30)        # 更新時間間隔
			#
			mouse_pressed = pygame.mouse.get_pressed()
			#
			if mouse_pressed[0]:  # 左クリック
				x, y = pygame.mouse.get_pos()
				x -= player.get_width() / 2
				y -= player.get_height() / 2
				#
			for event in pygame.event.get():
            	# 画面の閉じるボタンを押したとき
				if event.type == QUIT:
					pygame.quit()
					oDisp = 'Success'
					#sys.exit()		
					return		# ボタンから実行する時はsys.exit()でなくreturn
				# キーを押したとき
				if event.type == KEYDOWN:
					# ESCキーなら終了
					if event.key == K_ESCAPE:
						pygame.quit()
						oDisp = 'Success'
						#sys.exit()
						return			
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
def Test(*args):		# ボタンから実行する時は引数(*args)が必要
	main()

Pygame-)[General]マウスポインタでで画像(ボール)移動


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		(w,h) = (400,300)   # 画面サイズ
		(x,y) = (w/2, h/2)
		pygame.init()       # pygame初期化
		screen = pygame.display.set_mode((w, h))    # 大きさ300*200の画面を生成
		pygame.display.set_caption(u'マウスポインターでボール移動')   # タイトルバーに表示する文字
		#
		player = pygame.image.load('C:/Temp/basketball_a12.png').convert_alpha() 		# ボール画像の指定
		#
		while (1):
			screen.fill((100, 200, 200, 0))  # 画面の背景色
			screen.blit(player, (x, y)) # キャラの描画
			pygame.display.update()     # 画面更新
			pygame.time.wait(30)        # 更新時間間隔
			#
			for event in pygame.event.get():
				# マウスポインタで画像も移動
				if event.type == MOUSEMOTION:
					x, y = event.pos
					x -= int(player.get_width() / 2)
					y -= int(player.get_height() / 2)
            	# 画面の閉じるボタンを押したとき
				if event.type == QUIT:
					pygame.quit()
					oDisp = 'Success'
					#sys.exit()		
					return		# ボタンから実行する時はsys.exit()でなくreturn
				# キーを押したとき
				if event.type == KEYDOWN:
					# ESCキーなら終了
					if event.key == K_ESCAPE:
						pygame.quit()
						oDisp = 'Success'
						#sys.exit()
						return			
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
def Test(*args):		# ボタンから実行する時は引数(*args)が必要
	main()

Pygame-)[General]mp3形式ファイル再生

#!
#coding: utf-8
# python Marco
import pygame.mixer
import time
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
		#
def main():
	try:
		pygame.mixer.init(frequency = 44100)    # 初期設定
		pygame.mixer.music.load('C:/Temp/flashing.mp3')     # 音楽ファイルの読み込み
		pygame.mixer.music.play(1)              # 音楽の再生回数(1回)
		time.sleep(5)							# 音楽の再生時間: 5秒
		pygame.mixer.music.stop()               # 再生の終了
		oDisp = "Success"
		#sys.exit()
		return		# ボタンから実行する時はsys.exit()でなくreturn			
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
def Test(*args):		# ボタンから実行する時は引数(*args)が必要
	main()

Pygame-)[General]ブロック崩し


#!
#coding: utf-8
# python Marco
import pygame
from pygame.locals import *
import math
import pygame.mixer
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
#	"""shows message."""
		desktop = XSCRIPTCONTEXT.getDesktop()
		frame = desktop.getCurrentFrame()
		window = frame.getContainerWindow()
		toolkit = window.getToolkit()
		msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
		return msgbox.execute()
# 画面サイズ
SCREEN = Rect(0, 0, 400, 400)
#
# バドルのクラス
class Paddle(pygame.sprite.Sprite):
    # コンストラクタ(初期化メソッド)
    def __init__(self, filename):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = pygame.image.load(filename).convert()
        self.rect = self.image.get_rect()
        self.rect.bottom = SCREEN.bottom - 20          # パドルのy座標
		#
    def update(self):
        self.rect.centerx = pygame.mouse.get_pos()[0]  # マウスのx座標をパドルのx座標に
        self.rect.clamp_ip(SCREEN)                     # ゲーム画面内のみで移動
		#
# ボールのクラス
class Ball(pygame.sprite.Sprite):
    # コンストラクタ(初期化メソッド)
    def __init__(self, filename, paddle, blocks, score, speed, angle_left, angle_right):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = pygame.image.load(filename).convert()
        self.rect = self.image.get_rect()
        self.dx = self.dy = 0  # ボールの速度
        self.paddle = paddle  # パドルへの参照
        self.blocks = blocks  # ブロックグループへの参照
        self.update = self.start # ゲーム開始状態に更新
        self.score = score
        self.hit = 0  # 連続でブロックを壊した回数
        self.speed = speed # ボールの初期速度
        self.angle_left = angle_left # パドルの反射方向(左端:135度)
        self.angle_right = angle_right # パドルの反射方向(右端:45度)
		#
    # ゲーム開始状態(マウスを左クリック時するとボール射出)
    def start(self):
        # ボールの初期位置(パドルの上)
        self.rect.centerx = self.paddle.rect.centerx
        self.rect.bottom = self.paddle.rect.top
		#
        # 左クリックでボール射出
        if pygame.mouse.get_pressed()[0] == 1:
            self.dx = 0
            self.dy = -self.speed
            self.update = self.move
			#
    # ボールの挙動
    def move(self):
        self.rect.centerx += self.dx
        self.rect.centery += self.dy
		#
        # 壁との反射
        if self.rect.left < SCREEN.left:    # 左側
            self.rect.left = SCREEN.left
            self.dx = -self.dx              # 速度を反転
        if self.rect.right > SCREEN.right:  # 右側
            self.rect.right = SCREEN.right
            self.dx = -self.dx
        if self.rect.top < SCREEN.top:      # 上側
            self.rect.top = SCREEN.top
            self.dy = -self.dy
			#
        # パドルとの反射(左端:135度方向, 右端:45度方向, それ以外:線形補間)
        # 2つのspriteが接触しているかどうかの判定
        if self.rect.colliderect(self.paddle.rect) and self.dy > 0:
            self.hit = 0                                # 連続ヒットを0に戻す
            (x1, y1) = (self.paddle.rect.left - self.rect.width, self.angle_left)
            (x2, y2) = (self.paddle.rect.right, self.angle_right)
            x = self.rect.left                          # ボールが当たった位置
            y = (float(y2-y1)/(x2-x1)) * (x - x1) + y1  # 線形補間
            angle = math.radians(y)                     # 反射角度
            self.dx = self.speed * math.cos(angle)
            self.dy = -self.speed * math.sin(angle)
            pygame.mixer.music.load('C:/Temp/flying_pan.mp3')    # ブロックにボールが衝突した時の効果音取得
            pygame.mixer.music.play(1)              # 音楽の再生回数(1回)
			#
        # ボールを落とした場合
        if self.rect.top > SCREEN.bottom:
            self.update = self.start                    # ボールを初期状態に
            pygame.mixer.music.load('C:/Temp/badend1.mp3')    # ゲームオーバー時の効果音取得
            pygame.mixer.music.play(1)              # 音楽の再生回数(1回)
            #
            self.hit = 0
            self.score.add_score(-100)                  # スコア減点-100点
			#
        # ボールと衝突したブロックリストを取得(Groupが格納しているSprite中から、指定したSpriteと接触しているものを探索)
        blocks_collided = pygame.sprite.spritecollide(self, self.blocks, True)
        if blocks_collided:  # 衝突ブロックがある場合
            oldrect = self.rect
            for block in blocks_collided:
                # ボールが左からブロックへ衝突した場合
                if oldrect.left < block.rect.left and oldrect.right < block.rect.right:
                    self.rect.right = block.rect.left
                    self.dx = -self.dx
            		#        
                # ボールが右からブロックへ衝突した場合
                if block.rect.left < oldrect.left and block.rect.right < oldrect.right:
                    self.rect.left = block.rect.right
                    self.dx = -self.dx
					#
                # ボールが上からブロックへ衝突した場合
                if oldrect.top < block.rect.top and oldrect.bottom < block.rect.bottom:
                    self.rect.bottom = block.rect.top
                    self.dy = -self.dy
					#
                # ボールが下からブロックへ衝突した場合
                if block.rect.top < oldrect.top and block.rect.bottom < oldrect.bottom:
                    self.rect.top = block.rect.bottom
                    self.dy = -self.dy
                    #
                pygame.mixer.music.load('C:/Temp/flashing.mp3')    # パドルにボールが衝突した時の効果音取得
                pygame.mixer.music.play(1)	# 音楽の再生回数(1回)
                #
                self.hit += 1               # 衝突回数
                self.score.add_score(self.hit * 10)   # 衝突回数に応じてスコア加点
				#
# ブロックのクラス
class Block(pygame.sprite.Sprite):
    def __init__(self, filename, x, y):
        pygame.sprite.Sprite.__init__(self, self.containers)
        self.image = pygame.image.load(filename).convert()
        self.rect = self.image.get_rect()
        # ブロックの左上座標
        self.rect.left = SCREEN.left + x * self.rect.width
        self.rect.top = SCREEN.top + y * self.rect.height
		#
# スコアのクラス
class Score():
    def __init__(self, x, y):
        self.sysfont = pygame.font.SysFont(None, 20)
        self.score = 0
        (self.x, self.y) = (x, y)
    def draw(self, screen):
        img = self.sysfont.render("SCORE:"+str(self.score), True, (255,255,250))
        screen.blit(img, (self.x, self.y))
    def add_score(self, x):
        self.score += x
		#
def main():
	try:
		pygame.init()
		screen = pygame.display.set_mode(SCREEN.size)
		#
		# 描画用のスプライトグループ
		group = pygame.sprite.RenderUpdates()  
		#
		# 衝突判定用のスプライトグループ
		blocks = pygame.sprite.Group()
		#
		# スプライトグループに追加
		Paddle.containers = group
		Ball.containers = group
		Block.containers = group, blocks
		#
		# パドルの作成
		paddle = Paddle('C:/Temp/paddle.png')
		#
		# ブロックの作成(14*10)
		for x in range(1, 15):
			for y in range(1, 11):
				Block('C:/Temp/block.png', x, y)
				#		
		# スコアを画面(10, 10)に表示
		score = Score(10, 10)
		#
		# ボールを作成
		Ball('C:/Temp/ball.png',paddle, blocks, score, 5, 135, 45)
		#
		clock = pygame.time.Clock()
		#
		while (1):
			clock.tick(60)      # フレームレート(60fps)
			screen.fill((0,20,0))
			# 全てのスプライトグループを更新
			group.update()
			# 全てのスプライトグループを描画
			group.draw(screen)
			# スコアを描画
			score.draw(screen)
			# 画面更新
			pygame.display.update()
			#	
			# キーイベント(終了)
			for event in pygame.event.get():
				if event.type == QUIT:
					pygame.quit()
					oDisp =u'X終了'
					#sys.exit()
					return		# ボタンから実行する時はsys.exit()でなくreturn	
				if event.type == KEYDOWN and event.key == K_ESCAPE:
					pygame.quit()
					oDisp =u'ESC終了'
					#sys.exit()
					return		# ボタンから実行する時はsys.exit()でなくreturn	
	except Exception as er:
		pygame.quit() 
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
		sys.exit()
	finally:
		omsgbox(oDisp,1,'LO6.4.3.2(x64)')
def Test(*args):		# ボタンから実行する時は引数(*args)が必要
	main()
#
# 西住工房/【Pygame】ブロック崩しの作り方(効果音付き)より(一部、変更しています。)
# 効果音:flashing.mp3、flying_pan.mp3、badend1.mp3 は 無料効果音で遊ぼう! / ゲーム・アニメ調より

Pygame-)[General]





Pyautogui

Pyautogui-)[General]マウスカーソル操作(1)


#!
#coding: utf-8
# python Marco
import pyautogui
import time
import uno
import sys, traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		pyautogui.moveTo(300,300)
		oPos = pyautogui.position()
		oDisp = '移動前:' + str(oPos)
		pyautogui.moveRel(200,0, duration=1.0)
		pyautogui.moveRel(0,200, duration=1.0)
		pyautogui.moveRel(-200,0, duration=1.0)
		pyautogui.moveRel(0,-200, duration=1.0)
		oPos = pyautogui.position()
		oDisp = oDisp + '\n' + '移動後:' + str(oPos)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#[参考サイト]
# Why it doesn't work? / Python マウスとキーボードを制御する(マウスのクリック)

# Pythonでマウスやキーボードを操作できるPyAutoGUIによる自動操作マニュアル

Pyautogui-)[General]Screenshot


#!
#coding: utf-8
# python Marco
import webbrowser
import pyautogui
import time
import uno
import sys, traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		oURL = 'https://openoffice3.web.fc2.com/'
		if webbrowser.open(oURL,new=1,autoraise=1)== False:		# false is error
			raise webbrowser.Error
		# 5[sec]待機(Browser起動まで待機)
		time.sleep(5.0)
		# 指定範囲のScreenshot
		oSC = pyautogui.screenshot(region=(350, 200, 1000, 300))
		oSC.save('C:/Temp/Screen01.png')
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

Pyautogui-)[General]画面上のアイコンをクリック


#!
#coding: utf-8
# python Marco
import subprocess
import pyautogui
import time
import uno
import sys, traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		cmd='C:/Program Files/Mozilla Firefox/firefox.exe'
		oRtn = subprocess.call(cmd, shell=True)
		if oRtn != 0:
			oDisp = 'プロセスが異常終了しました'
			sys.exit()
		oPng = 'C:/Temp/yahoo.png'
		while pyautogui.locateOnScreen(oPng , confidence=0.9) is None:
			time.sleep(1)
		#Yahooのアイコンの位置を取得
		oPos = pyautogui.locateOnScreen(oPng , confidence=0.9)
		omsgbox(str(oPos),1,'LO7.0.1.2')
		#yahooのアイコンをクリック
		pyautogui.click(oPos)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
# ↓yahoo.png↓



Pyautogui-)[General]Browserを起動させて検索する


#!
#coding: utf-8
# python Marco
import pyautogui
import time
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		pyautogui.press('win')		#windowsキーを押す。
		time.sleep(1)
		pyautogui.typewrite('firefox')	#firefoxと入力
		pyautogui.press('enter')		#Enter keyを押す	
		time.sleep(4)	
		pyautogui.moveTo(550, 220) 	#Firefoxの検索テキストボックスの位置にカーソル移動
		pyautogui.click()			#マウスをclick
		time.sleep(4)
		pyautogui.typewrite('pyautogui')
		pyautogui.press('enter')
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

Pyautogui-)[General]pyautoguiを中断


#
#coding: utf-8
# python Marco
import pyautogui
import time
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		pyautogui.FAILSAFE = True #pyautoguiの中断を有効にする: 画面の左上端 座標(0,0)にマウスをもっていくと中断
		pyautogui.press('win')
		time.sleep(1)
		pyautogui.typewrite('firefox')
		pyautogui.press('enter')
		time.sleep(4)
		pyautogui.moveTo(550, 220) 
		pyautogui.click()
		time.sleep(4)
		pyautogui.typewrite('pyautogui')
		pyautogui.press('enter')
		oDisp = 'Success'
	except pyautogui.FailSafeException:
		oDisp = u'pyautogui.FAILSAFE実行'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

Pyautogui-)[General]





pywin32

[ FileSystemObject ]

ComWsNet-)[General]Network Information取得


#!
#coding: utf-8
# python Marco
import win32com.client
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		oFSObj = win32com.client.Dispatch('Scripting.FileSystemObject')
		oFile = 'C:/temp/output.csv'
		if oFSObj.FileExists(oFile) == True:
			oDisp = str(oFile) + ' は存在します'
		else:
			oDisp = str(oFile) + ' は存在しません'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.4.2')


[ WScript.Network ]

ComWsNet-)[General]Network Information取得


#!
#coding: utf-8
# python Marco
import win32com.client
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		oWNetObj = win32com.client.Dispatch('WScript.Network')
		oDomain = oWNetObj.UserDomain
		oComputer = oWNetObj.ComputerName
		oUser = oWNetObj.UserName
		oDisp = 'Domain =  ' + oDomain + '\n' + 'Computer =  ' + oComputer + '\n' + 'User Name =  ' + oUser
		oDisp = oDisp + '\n\n' + 'Seccess' + '\n' + '[ Windows10(64bit) ]'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

ComWsNet-)[General]





Win32 API

[ win32gui ]

win32gui-)[General]Desktop Windowsのhandle取得


#!
#coding: utf-8
# python Marco
import win32gui
import uno
import sys
import traceback

from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		hwnd = win32gui.GetDesktopWindow()
		oDisp = 'GetDesktopWindow\n = ' + str(hwnd)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#Python for Win32 Extensions Help / Module win32gui

win32gui-)[General]ウィンドウ全体のデバイスコンテキスト(DC)を取得


#!
#coding: utf-8
# python Marco
import win32gui
import uno
import sys
import traceback

from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		hwnd = win32gui.GetDesktopWindow()
		dc = win32gui.GetWindowDC(hwnd)
		oDisp = 'GetWindowDC\n = ' + str(dc)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#F-Basic Programming Tips / GetWindowDC

win32gui-)[General]現在操作中のウインドウのハンドルを取得する


#!
#coding: utf-8
# python Marco
import subprocess
import time
import win32gui
import uno
import sys
import traceback

from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		AppName = 'notepad.exe'
		p = subprocess.Popen(AppName)
		# 起動するまで待機
		time.sleep(1)
		# 起動したApplicationのハンドルを取得する
		hw1 = win32gui.GetForegroundWindow()
		oDisp = '[起動したApplicationのハンドル]\n 起動アプリ: ' + AppName + '\n' + ' GetForegroundWindow = ' + str(hw1)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#Programming Library / 120.現在操作中のウインドウのハンドルを取得する

win32gui-)[General]ウインドウのタイトルバーの文字列を取得


#!
#coding: utf-8
# python Marco
import subprocess
import time
import win32gui
import uno
import sys
import traceback

from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		AppName = 'notepad.exe'
		p = subprocess.Popen(AppName)
		# 起動するまで待機
		time.sleep(1)
		# 起動したApplicationのハンドルを取得する
		hw1 = win32gui.GetForegroundWindow()
		wtnm = win32gui.GetWindowText(hw1)
		oDisp = '[起動したアプリのWindowタイトル]\n 起動アプリ: ' + AppName + '\n' + ' GetWindowText = ' + str(wtnm)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#win32gui.GetWindowText

win32gui-)[General]ウィンドウの左上端と右下端の座標をスクリーン座標で取得


#!
#coding: utf-8
# python Marco
import subprocess
import time
import win32gui
import uno
import sys
import traceback

from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		AppName = 'notepad.exe'
		p = subprocess.Popen(AppName)
		# 起動するまで待機
		time.sleep(1)
		# 起動したApplicationのハンドルを取得する
		hw1 = win32gui.GetForegroundWindow()
		x0, y0, x1, y1 = win32gui.GetWindowRect(hw1)
		oDisp = '[起動したアプリのWindowサイズ]\n 起動アプリ: ' + AppName + '\n' + ' 左上端(X, Y) = (' + str(x0)+ ' , ' + str(y0) + ')\n 右下端(X, Y) = (' + str(x1) + ' , ' + str(y1) + ')'
	except Exception as e:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

win32gui-)[General]ウィンドウのタイトルを指定してhandle取得


#!
#coding: utf-8
# python Marco
import win32gui
import uno
import sys
import traceback

from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		#無題のCalcのタイトル(Windowのタイトル)を指定してハンドルを取得
		hw1 = win32gui.FindWindow(None,'無題 1 - LibreOffice Calc')
		oDisp = '[無題のCalcのハンドル]\n' + ' FindWindow = ' + str(hw1)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

win32gui-)[General]ウィンドウのタイトルを指定してウインドウサイズを変更

#!
#coding: utf-8
# python Marco
import win32gui
import uno
import sys
import traceback

from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		#無題のCalcのタイトル(Windowのタイトル)を指定してハンドルを取得
		oTitle = '無題 - メモ帳'
		hw1 = win32gui.FindWindow(None,oTitle)
		if hw1 == 0:
			oDisp = oTitle + 'が起動していませn。'
			sys.exit()
		win32gui.ShowWindow(hw1, 3)
		omsgbox('Windowサイズの最大化',1,'LO7.0.1.2')
		win32gui.ShowWindow(hw1, 9)
		omsgbox('Windowサイズを元に戻す',1,'LO7.0.1.2')
		win32gui.ShowWindow(hw1, 6)
		omsgbox('Windowサイズの最小化',1,'LO7.0.1.2')
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#Microsoft Doc / ShowWindow function (winuser.h)



win32gui-)[General]




win32gui-)[General]特定のwindowを最前面にする

#!
#coding: utf-8
# python Marco
import subprocess
import time
import win32gui
import win32process
import win32api
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		MOUSEEVENTF_LEFTDOWN = 0x2
		MOUSEEVENTF_LEFTUP = 0x4
		p = subprocess.Popen('notepad.exe')
		# 起動するまで待機
		time.sleep(1)
		# 起動したメモ帳のハンドルを取得する。
		hw1 = win32gui.GetForegroundWindow()
		(tid1, pid1) = win32process.GetWindowThreadProcessId(hw1)
		#
		current_threadid = win32api.GetCurrentThreadId()
		#
		# トップレベルウィンドウを切り替える(この時点ではフォーカスできていない)
		win32process.AttachThreadInput(current_threadid, tid1, True)
		win32gui.BringWindowToTop(hw1)
		win32process.AttachThreadInput(current_threadid, tid1, False)
		#
		# ウィンドウの左上の隅っこをクリックしてアクティブにする。
		(left, top, right, bottom) = win32gui.GetWindowRect(hw1)
		win32api.SetCursorPos((left + 1, top + 1))
		time.sleep(0.1)
		win32api.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0)
		time.sleep(0.1)
		win32api.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0)
		oDisp = 'Success'
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
#参考URL1:stamemo / ウィンドウを確実にアクティブにする方法
#参考URL2:teratail / windowsで特定のwindowを最前面にしたい


[ win32api ]

win32api-)[General]Diskspace取得


#!
#coding: utf-8
# python Marco
import win32api
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		oDS = win32api.GetDiskFreeSpaceEx('C:')
		oDisp = '利用可能Diskspace = ' + str(int(oDS[0]/1024**3)) + ' GB\n' 
		oDisp = oDisp + 'Total Diskspace = ' + str(int(oDS[1]/1024**3)) + ' GB\n'
		oDisp = oDisp + 'Total Free Diskspace = ' + str(int(oDS[2]/1024**3)) + ' GB' 
	except Exception as e:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

win32api-)[General]任意の時間処理を中断


#!
#coding: utf-8
# python Marco
import win32api
import datetime
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
#
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
#
def oTest():
	try:
		oNowB = str(datetime.datetime.now())
		# 5[sec]待機
		win32api.Sleep(5000)
		#
		oNowA = str(datetime.datetime.now())
		oDisp = u'[ 任意時間(5[sec])処理を中断 ]\n'
		oDisp = oDisp + oNowB + '\n\n' + oNowA
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')

win32api-)[General]





pythonnet

Pynet-)[General]System.Collection


#!
#coding: utf-8
# python Marco
import clr
from System.Collections.Generic import List
import uno
import sys
import traceback
from com.sun.star.awt.MessageBoxType import MESSAGEBOX
def omsgbox(oMessage='',oBtnType=1,oTitle='Title'):
	"""shows message."""
	desktop = XSCRIPTCONTEXT.getDesktop()
	frame = desktop.getCurrentFrame()
	window = frame.getContainerWindow()
	toolkit = window.getToolkit()
	msgbox = toolkit.createMessageBox(window, MESSAGEBOX, oBtnType, oTitle, oMessage)
	return msgbox.execute()
def oTest():
	try:
		clr.AddReference('System.Collections')
		lst = List[int]()
		lst.Add(3)
		lst.Add(5)
		lst.Add(1)
		lst.Sort()
		oDisp = '[System.Collections]'
		for x in lst:
			oDisp = oDisp + '\n' + str(x)
	except Exception as er:
		oDisp = ''
		oDisp = str(traceback.format_exc()) + '\n' + str(er)
	finally:
		omsgbox(oDisp,1,'LO7.0.1.2')
#
# Pythonのコードから.NETを呼び出す

win32api-)[General]





Top of Page

inserted by FC2 system