注意判断读取文件是否成功用 img is None 不是 img == None:
import cv2
def displayOneImage() :
srcFile = "F:\\deep\data\\dataForStudyOpencv\\1_869307B00644_20190312_052816_410.bmp"
img = cv2.imread( srcFile )
if img is None :
print("Fail to load pic")
return
winName = 'displayOneImage'
cv2.namedWindow( winName , cv2.WINDOW_NORMAL )
cv2.imshow( winName , img )
def findTemplate() :
srcFile = "F:\\deep\data\\dataForStudyOpencv\\1_869307B00644_20190312_052816_410.bmp"
dstFile = "F:\\deep\data\\dataForStudyOpencv\\1_869307B00644_20190312_052816_410_templateMarked.png"
templateFile = "F:\\deep\data\\dataForStudyOpencv\\template1.png"
img = cv2.imread( srcFile )
if img is None :
return ;
imgTempl = cv2.imread( templateFile ) ;
w,h = imgTempl.shape[:-1]
print( "imgTempl.shape:" , imgTempl.shape )
print("w,h:" , w,h )
find = cv2.matchTemplate( img , imgTempl , cv2.TM_CCORR_NORMED )
minVal , maxVal , minLoc , maxLoc = cv2.minMaxLoc( find )
bottom_right = (maxLoc[0] + w , maxLoc[1]+h)
print('maxVal:', maxVal , 'maxLoc:' , maxLoc )
print('bottom_right:', bottom_right )
cv2.rectangle( img , maxLoc , bottom_right , (255,255,255) , 20 )
winName = 'findTemplate'
cv2.namedWindow( winName , cv2.WINDOW_NORMAL )
cv2.imshow( winName , img )
cv2.imwrite( dstFile , img )
def loop() :
k = cv2.waitKey(0)
if ( k== 27 ) :
cv2.destroyAllWindows()
def main() :
displayOneImage()
findTemplate()
loop()
main()
import cv2
def displayOneImage() :
srcFile = "F:\\deep\data\\dataForStudyOpencv\\1_869307B00644_20190312_052816_410.bmp"
img = cv2.imread( srcFile )
if img is None :
print("Fail to load pic")
return
winName = 'displayOneImage'
cv2.namedWindow( winName , cv2.WINDOW_NORMAL )
cv2.imshow( winName , img )
def findTemplate() :
srcFile = "F:\\deep\data\\dataForStudyOpencv\\1_869307B00644_20190312_052816_410.bmp"
dstFile = "F:\\deep\data\\dataForStudyOpencv\\1_869307B00644_20190312_052816_410_templateMarked.png"
templateFile = "F:\\deep\data\\dataForStudyOpencv\\template1.png"
img = cv2.imread( srcFile )
if img is None :
return ;
imgTempl = cv2.imread( templateFile ) ;
w,h = imgTempl.shape[:-1]
print( "imgTempl.shape:" , imgTempl.shape )
print("w,h:" , w,h )
find = cv2.matchTemplate( img , imgTempl , cv2.TM_CCORR_NORMED )
minVal , maxVal , minLoc , maxLoc = cv2.minMaxLoc( find )
bottom_right = (maxLoc[0] + w , maxLoc[1]+h)
print('maxVal:', maxVal , 'maxLoc:' , maxLoc )
print('bottom_right:', bottom_right )
cv2.rectangle( img , maxLoc , bottom_right , (255,255,255) , 20 )
winName = 'findTemplate'
cv2.namedWindow( winName , cv2.WINDOW_NORMAL )
cv2.imshow( winName , img )
cv2.imwrite( dstFile , img )
def loop() :
k = cv2.waitKey(0)
if ( k== 27 ) :
cv2.destroyAllWindows()
def main() :
displayOneImage()
findTemplate()
loop()
main()