Skip to content

Instantly share code, notes, and snippets.

@merlinboii
Created May 21, 2022 07:41
Show Gist options
  • Save merlinboii/c9d54c99e2f33fceee61a8c6f1de4404 to your computer and use it in GitHub Desktop.
Save merlinboii/c9d54c99e2f33fceee61a8c6f1de4404 to your computer and use it in GitHub Desktop.
import cv2
import cv2
import numpy as np
import matplotlib.pyplot as plt
import math
import mysql.connector
# @desc connect MySQL database
mydb = mysql.connector.connect(
host="slotracha168.com",
user="slotrac_blue",
password="blue1234567890",
database="blue_db"
)
# rotate point
# @desc rotate function
# @params point(x,y), degree to rotate
def rotate2D(point, deg):
rads = math.radians(deg) # convert degrees to radians for calculatig COS,SIN ...
x, y = point # extract point to x, y
rcos = math.cos(rads) # define COS(radians)
rsin = math.sin(rads) # define SIN(radians)
rx = x * rcos - y * rsin # define rx by calculate -> xCOS(radians) - ySIN(radians)
ry = x * rsin + y * rcos # define ry by calculate -> xSIN(radians) + yCOS(radians)
rx = round(rx) # line 27-28: round up/down resulting in 1 digit decimal -> round(5.5423) = 6, round(5.3423) = 5
ry = round(ry)
point[0] = rx # line 29-30: assign point[0:rx, 1:ry]
point[1] = ry
# translate point
def translate2D(src, target, sign):
tx, ty = target
src[0] += tx * sign
src[1] += ty * sign
nr_im = 9876 # define nr_im
font = cv2.FONT_HERSHEY_SIMPLEX # define font by use cv2 font type: FONT_HERSHEY_SIMPLEX
fontScale = 1 # define font size
colorText = (0, 0, 255) # define text color
thickness = 2 # define font bold
# define a video capture object
vid = cv2.VideoCapture(0) # parameter: 0 is camaera_id of the video capturing device to open. -> returns video from the first webcam on your computer
while(True): # define forever loop -> passing condition with 1 or true makes could forever loop
# Capture the video frame
# by frame
ret, frame = vid.read() # read vdo frame that receive from camera -> returns a tuple (return value, image) -> ret: boolean, frame: image
# in this code we do not use `ret`
img = frame # assing received frame to img
img = cv2.resize(img, (512 , 512)) # resize image with desired size(512*512)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert BGR image to Gray scale; FYI: almost of raw images are BGR type.
blurred = cv2.GaussianBlur(gray, (7, 7), 0) # make image smooth and reduce noise -> with Gaussian filter.
ret,mask = cv2.threshold(blurred,120,255,cv2.THRESH_BINARY_INV) # apply thresholding, If the pixel value is smaller than the threshold, it is set to 0, otherwise it is set to a maximum value
# READ DOCs: https://docs.opencv.org/4.x/d7/d4d/tutorial_py_thresholding.html
# Find contours
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # find contours of mask with properties -> For property meaing READ: https://phyblas.hinaboshi.com/oshi13
contours = sorted(contours,key=cv2.contourArea, reverse = True)[:1] # sort descending contours value that receive from line 63 by contourArea
# ex. x=[2,3,4] -> x[:1] = [2], x=[[1,2,3],[4,5,6]] -> x[:1] = [[1,2,3]]
for c in contours: # start loop
# approximate the contour
x,y,w,h = cv2.boundingRect(c) # draw an approximate rectangle around the binary image, in this case image passed is c -> return X coordinate, Y coordinate, Width, Height
print('x,y,w,h',x,y,w,h)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) #165mm = 338 pixels # 1 pixel = 0.48 mm
# draw a rectangle on any image with x,y,w,h value.
if w >= 200: # condition check if w(width) greater than 200 ? if TRUE do line 73-218, else go to next round of loop(if exist, if not go to line 223)
roi=mask[y:y+h,x:x+w] # select some part of mask(receive from line 60) follow [y:y+h,x:x+w]
cv2.imshow("roi", roi) # show the selected image
t_side = round((57.5*338) / 165) # calculate t_side by round value of ((57.5*338) / 165)
print('t_side',t_side)
print('w-t_side',w-t_side)
top_side = roi[1:500,1:118] #57.5mm = 286 pixels # select some part of roi follow [1:500,1:118] to be top_side
cv2.imshow("top_side", top_side)
mid_side = roi[1:500,150:250] #that 1 pixel = 0.17 mm # select some part of roi follow[1:500,1:250] to be mid_side
cv2.imshow("mid_side", mid_side)
bottom_side = roi[1:500,w-100:w] #that 1 pixel = 0.17 mm # select some part of roi follow [1:500,w-100:w] to be bottom_side
cv2.imshow("bottom_side", bottom_side)
point_pixel = [2,4,5,8,10] # define point_pixel for start side
########################################################################
###################### Start Side ####################################
########################################################################
print('------------------------- Start Side --------------------------')
count_frist = 0 # define count value for start side
height_mm_first=[] # define height as array value for start side
for xf in point_pixel: # loop with point_pixel -> round1: wf=2, round2: wf=4, round3: wf=4, .. so on following values in point_pixel
count_frist = count_frist+1 # count increatment
#print(x)
first_5points = top_side[1:h,xf] # select some part of top_side follow [1:h,xf], assign to first_5points
#cv2.imshow("first_5points_"+str(count_frist), first_5points)
# Find contours
contoursfirst_5points, _ = cv2.findContours(first_5points, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # act like line 63, find contours of first_5points
contoursfirst_5points = sorted(contoursfirst_5points,key=cv2.contourArea, reverse = True)[:1] # act like line 64, sort descending contoursfirst_5points value by contourArea.
for cfirst_5points in contoursfirst_5points: #loop
# approximate the contour
xfirst_5points,yfirst_5points,wfirst_5points,hfirst_5points = cv2.boundingRect(cfirst_5points) # draw an approximate rectangle around the binary image, in this case image passed is cfirst_5points
#print('xfirst_5points,yfirst_5points,wfirst_5points,hfirst_5points',xfirst_5points,yfirst_5points,wfirst_5points,hfirst_5points)
height_mm_first_5points = hfirst_5points*0.225528 # calculate height
#print('height_mm first_5points_'+str(count_frist),height_mm_first_5points)
height_mm_first.append(height_mm_first_5points) # add height_mm_first_5points to array height_mm_first
#print('height_mm_first',height_mm_first)
point1_first = height_mm_first[0] # define point1_first
point2_first = height_mm_first[1] # define point2_first
point3_first = height_mm_first[2] # define point3_first
point4_first = height_mm_first[3] # define point4_first
point5_first = height_mm_first[4] # define point5_first
print('point1_first',point1_first)
print('point2_first',point2_first)
print('point3_first',point3_first)
print('point4_first',point4_first)
print('point5_first',point5_first)
avg_first_points = sum(height_mm_first) / 5 # calculate average
print('avg_first_points',avg_first_points)
########################################################################
###################### Mid Side ####################################
########################################################################
print('------------------------- Mid Side --------------------------')
count_mid = 0 # define count value for mid side
height_mm_mid=[] # define height as array value for mid side
point_pixel_mid = [2,4,6,8,10] # define point_pixel for mid side
for xf in point_pixel_mid: # do like in Start Side but change value
count_mid = count_mid+1
#print(x)
mid_5points = mid_side[1:h,xf]
#cv2.imshow("first_5points_"+str(count_frist), first_5points)
# Find contours
contoursmid_5points, _ = cv2.findContours(mid_5points, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # act like line 63,
contoursmid_5points = sorted(contoursmid_5points,key=cv2.contourArea, reverse = True)[:1] # act like line 64,
for cmid_5points in contoursmid_5points:
# approximate the contour
xmid_5points,ymid_5points,wmid_5points,hmid_5points = cv2.boundingRect(cmid_5points)
#print('xmid_5points,ymid_5points,wmid_5points,hmid_5points',xmid_5points,ymid_5points,wmid_5points,hmid_5points)
height_mm_mid_5points = hmid_5points*0.33348
#print('height_mm mid_5points_' + str(count_mid),height_mm_mid_5points)
height_mm_mid.append(height_mm_mid_5points)
point1_mid = height_mm_mid[0]
point2_mid = height_mm_mid[1]
point3_mid = height_mm_mid[2]
point4_mid = height_mm_mid[3]
point5_mid = height_mm_mid[4]
print('point1_mid',point1_mid)
print('point2_mid',point2_mid)
print('point3_mid',point3_mid)
print('point4_mid',point4_mid)
print('point5_mid',point5_mid)
avg_mid_points = sum(height_mm_mid) / 5
print('avg_mid_points',avg_mid_points)
########################################################################
###################### End Side ####################################
########################################################################
print('------------------------- End Side --------------------------')
count_end = 0 # define count value for end side
height_mm_end=[] # define height as array value for end side
point_pixel_end = [2,4,6,8,10] # define point_pixel for end side
for xe in point_pixel_end: # do like in Start Side but change value
#print('w-xe', w-xe)
count_end=count_end+1
#print('w,t_side,xe',xe)
end_5points = bottom_side[1:500,xe]
#cv2.imshow("end_5points_"+str(count_end), end_5points)
# Find contours
contoursend_5points, _ = cv2.findContours(end_5points, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # act like line 63,
contoursend_5points = sorted(contoursend_5points,key=cv2.contourArea, reverse = True)[:1] # act like line 64,
for cend_5points in contoursend_5points:
# approximate the contour
xend_5points,yend_5points,wend_5points,hend_5points = cv2.boundingRect(cend_5points)
#print('xend_5points,yend_5points,wend_5points,hend_5points',xend_5points,yend_5points,wend_5points,hend_5points)
height_mm_end_5points = hend_5points*0.26155
#print('height_mm end_5points_'+str(count_end),height_mm_end_5points)
height_mm_end.append(height_mm_end_5points)
point1_end = height_mm_end[0]
point2_end = height_mm_end[1]
point3_end = height_mm_end[2]
point4_end = height_mm_end[3]
point5_end = height_mm_end[4]
print('point1_end',point1_end)
print('point2_end',point2_end)
print('point3_end',point3_end)
print('point4_end',point4_end)
print('point5_end',point5_end)
avg_end_points = sum(height_mm_end) / 5
print('avg_end_points',avg_end_points)
mycursor = mydb.cursor() # create cursor object -> point to Database that is connected at line 10
# SQL command to insert data to database -> Syntax: INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
sql = "INSERT INTO For_EX1 (point1_first,point2_first,point3_first,point4_first,point5_first,point1_mid,point2_mid,point3_mid,point4_mid,point5_mid,point1_end,point2_end,point3_end,point4_end,point5_end,avg_first_points,avg_mid_points,avg_end_points) VALUES (%s,%s, %s,%s, %s,%s,%s, %s,%s, %s,%s,%s, %s,%s, %s, %s,%s, %s)"
# values to insert -> these gonna replace %s order by order in the line 215.
val = (point1_first,point2_first,point3_first,point4_first,point5_first,point1_mid,point2_mid,point3_mid,point4_mid,point5_mid,point1_end,point2_end,point3_end,point4_end,point5_end,avg_first_points,avg_mid_points,avg_end_points)
# run execute the SQL command above
mycursor.execute(sql, val)
# confirm the changes made by the user to the database
mydb.commit()
print(mycursor.rowcount, "record inserted.")
cv2.imshow('img', img) # show img
cv2.imshow('frame', frame) # show frame that is defined at line 51
# the 'q' button is set as the
# quitting button you may use any
# desired button of your choice
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# After the loop release the cap object
vid.release()
# Destroy all the windows
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment