import cv2
import os
def load_all_files(folder_path):
files = os.listdir(folder_path)
img_files = []
for x in files:
if x.endswith('.jpg') or x.endswith('.png'):
img_files.append(os.path.join(folder_path,x))
return img_files
mouseX = 0
mouseY = 0
color = [255,0,0]
def get_rect_pos(file):
outter_pts = []
inner_pts = []
mode = 0
def draw_circle(event,x,y,flags,param):
global mouseX,mouseY,color
if event == cv2.EVENT_LBUTTONDBLCLK:
if mode == 0:
outter_pts.append((x,y))
else:
color = [0,0,255]
inner_pts.append((x,y))
cv2.circle(img,(x,y),10,(color[0],color[1],color[2]),-1)
global mouseX,mouseY
mouseX,mouseY = x,y
#else if event == cv2.EVENT_RBUTTONCLK:
# quit = True
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
img = cv2.imread(file)
while( 1 ):
cv2.imshow('image',img)
k = cv2.waitKey(20) & 0xFF
if k == 27:#esc
break
if k == 32:#space
mode = 1
print('switch to inner pts')
elif k == ord('a'):
#global mouseX,mouseY
#print(mouseX,mouseY)
print('outter')
for x in outter_pts:
print(x[0],x[1])
print('inner')
for x in inner_pts:
print(x[0],x[1])
return outter_pts,inner_pts
def draw_lines(img_path,outter_pts,inner_pts):
img = cv2.imread(img_path)
#draw lines
cv2.line(img,outter_pts[0],outter_pts[1],(255,0,0),3)
cv2.line(img,outter_pts[0],outter_pts[3],(255,0,0),3)
cv2.line(img,outter_pts[2],outter_pts[3],(255,0,0),3)
cv2.line(img,outter_pts[2],outter_pts[1],(255,0,0),3)
cv2.line(img,inner_pts[0],inner_pts[1],(0,0,255),3)
cv2.line(img,inner_pts[0],inner_pts[3],(0,0,255),3)
cv2.line(img,inner_pts[2],inner_pts[3],(0,0,255),3)
cv2.line(img,inner_pts[2],inner_pts[1],(0,0,255),3)
def draw_line(pt0,pt1,pt2,pt3,ratio,color):
cv2.line(img,((int)(pt0[0]*(1-ratio) + pt3[0]*ratio),(int)(pt0[1]*(1-ratio) + pt3[1]*ratio)) ,\
((int)(pt1[0]*(1-ratio) + pt2[0]*ratio),(int)(pt1[1]*(1-ratio) + pt2[1]*ratio)),color,3)
cv2.line(img,((int)(pt0[0]*(1-ratio) + pt1[0]*ratio),(int)(pt0[1]*(1-ratio) + pt1[1]*ratio)) ,\
((int)(pt3[0]*(1-ratio) + pt2[0]*ratio),(int)(pt3[1]*(1-ratio) + pt3[1]*ratio)),color,3)
draw_line(outter_pts[0],outter_pts[1],outter_pts[2],outter_pts[3],0.3333,(255,0,0))
draw_line(outter_pts[0],outter_pts[1],outter_pts[2],outter_pts[3],0.6666,(255,0,0))
draw_line(inner_pts[0],inner_pts[1],inner_pts[2],inner_pts[3],0.3333,(0,0,255))
draw_line(inner_pts[0],inner_pts[1],inner_pts[2],inner_pts[3],0.6666,(0,0,255))
#cv2.setMouseCallback('image',None)
#cv2.imshow("image",img)
#cv2.waitKey()
cv2.imwrite(img_path+'_with_grid.jpg',img)
import sys
if __name__ == '__main__':
folder_path = r"E:\origin"
if len(sys.argv) > 1:
folder_path = sys.argv[1]
img_files = load_all_files(folder_path)
outter_pts,inner_pts = get_rect_pos(img_files[0])#r"E:\origin\img1.png")
for x in img_files:
draw_lines(x,outter_pts,inner_pts)