├── .gitignore ├── GflAx.dll ├── LICENSE ├── lib ├── circle.ahk ├── misc.ahk ├── quad.ahk └── triangle.ahk ├── readme.md ├── shape_recog.ahk └── shape_recog.exe /.gitignore: -------------------------------------------------------------------------------- 1 | temp.ahk 2 | -------------------------------------------------------------------------------- /GflAx.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aviaryan/shape-recog/08793ccbd5a915152021e6e14a21ed5e78e81741/GflAx.dll -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /lib/circle.ahk: -------------------------------------------------------------------------------- 1 | 2 | validateCircle(){ 3 | rh := PXR-PXL 4 | rv := PYT-PYB 5 | rmin := rh>rv ? rv : rh 6 | if ( (rh*CIRCACC) < abs(PXT-PXB) ) 7 | return -1 8 | if ( (rv*CIRCACC) < abs(PYL-PYR) ) 9 | return -1 10 | 11 | if ( distance(COORDS[1], COORDS[COORDS.MaxIndex()]) > (CIRC_DIST_APART*rmin) ) ; check for figure closing 12 | return -1 13 | ; for circle rh == rv 14 | 15 | if ( (rmin*CIRCACC) < abs(rh-rv) ) ; if points are aligned then only show OVAL 16 | return -1 ;ID_OVAL 17 | return drawCircle() 18 | } 19 | 20 | drawCircle(x="", y="", d=""){ 21 | if !x 22 | getCircle(x, y, d) 23 | d /= 2 24 | plt := initDrawing() 25 | plt.DrawCircle(x, 400-y, d) 26 | plt.SaveBitmap("i") 27 | plt := "" 28 | return ID_CIR 29 | } 30 | 31 | forceCheckCircle(){ 32 | z := COORDS.maxIndex() 33 | da := {} , xa := {} , ya := {} 34 | getCircle(x, y, d, xa, ya, da) 35 | df := d/4 36 | s := 1 37 | loop % z 38 | { 39 | if (distance(x "-" y, xa[A_Index] "-" ya[A_Index]) > df){ 40 | s := 0 41 | break 42 | } 43 | if (abs(d-da[A_index]) > df){ 44 | s := 0 45 | break 46 | } 47 | } 48 | if (s==0) 49 | return -1 50 | else { 51 | return drawCircle(x,y,d) 52 | } 53 | } 54 | 55 | getCircle(Byref xps, Byref yps, Byref dps, Byref xa="", Byref ya="", Byref da=""){ 56 | z := COORDS.maxIndex() 57 | xps := 0 , yps := 0, dps := 0 58 | da := {} 59 | xa := {} 60 | ya := {} 61 | loop % z 62 | { 63 | p := COORDS[A_index] 64 | maxd := 0 65 | loop % z 66 | { 67 | p2 := COORDS[A_Index] 68 | if (p==p2) 69 | continue 70 | d := distance(p2, p) 71 | if (d>maxd){ 72 | maxd := d 73 | pt := p2 74 | } 75 | } 76 | givePoints(p, x0, y0) 77 | givePoints(pt, x1, y1) 78 | xps += (x0+x1)/2 79 | yps += (y0+y1)/2 80 | dps += maxd 81 | 82 | xa.Insert((x0+x1)/2) 83 | ya.Insert((y0+y1)/2) 84 | da.Insert( maxd ) 85 | } 86 | xps /= z 87 | yps /= z 88 | dps /= z 89 | } 90 | 91 | validateLine(){ 92 | acbk := ACC 93 | ACC := 10*PI/180 94 | distantCOORDS(10) 95 | detectCorners() 96 | ACC := acbk 97 | if CORNS.maxIndex() 98 | return -1 99 | else 100 | return drawLine() ;ID_LINE 101 | } 102 | 103 | drawLine(){ 104 | if !COORDS.maxIndex() 105 | return ID_LINE 106 | plt := initDrawing() 107 | givePointsInv(COORDS[1], p0x, p0y) 108 | givePointsInv(COORDS[COORDS.maxIndex()], p1x, p1y) 109 | plt.DrawLine(p0x, p0y, p1x, p1y) 110 | plt.SaveBitmap("i") 111 | ObjRelease(plt) 112 | return ID_LINE 113 | } -------------------------------------------------------------------------------- /lib/misc.ahk: -------------------------------------------------------------------------------- 1 | /* 2 | PROGRAM BASED FS 3 | */ 4 | 5 | resolveShapeId(ID){ 6 | if (id == ID_LINE) 7 | return "LINE" 8 | else if (id == ID_TRI) 9 | return "TRIANGLE" 10 | else if (id == ID_SQ) 11 | return "SQUARE" 12 | else if (id == ID_RECT) 13 | return "RECTANGLE" 14 | else if (id == ID_CIR) 15 | return "CIRCLE" 16 | else if (id == ID_QUAD) 17 | return "INVALID (QUAD)" 18 | else if (id == ID_DIST) 19 | return "INVALID (DIST_ERROR)" 20 | else if (id == ID_OVAL) 21 | return "INVALID (OVAL)" 22 | else if (id < 0) 23 | return "INVALID" 24 | } 25 | 26 | distance(p1, p2){ 27 | givePoints(p2, p2x, p2y) 28 | givePoints(p1, p1x, p1y) 29 | return Sqrt( (p2y-p1y)**2 + (p2x-p1x)**2 ) 30 | } 31 | 32 | givePoints(p1, byref x1, byref y1){ 33 | if (Instr(p1,"-")==1) 34 | sp := Instr(p1, "-", 0, 2) 35 | else 36 | sp := Instr(p1, "-") 37 | x1 := Substr(p1, 1, sp-1) 38 | y1 := Substr(p1, sp+1) 39 | } 40 | 41 | givePointsInv(p1, byref x1, byref y1){ 42 | givePoints(p1, x1, y1) 43 | y1 := 400-y1 44 | } 45 | 46 | pIntersectStart(ByRef x, ByRef y){ 47 | ; http://en.wikipedia.org/wiki/Line%E2%80%93line_intersection#Given_two_points_on_each_line 48 | givePoints(COORDS[1], x1, y1) 49 | givePoints(CORNS[1], x2, y2) 50 | givePoints(CORNS[CORNS.maxIndex()], x3, y3) 51 | givePoints(COORDS[COORDS.maxIndex()], x4, y4) 52 | d := (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4) 53 | if (d==0){ 54 | x = -1 55 | y = -1 56 | return 57 | } 58 | part1 := x1*y2 - y1*x2 59 | part2 := x3*y4 - y3*x4 60 | x := part1*(x3-x4) - (x1-x2)*part2 61 | x/=d 62 | y := part1*(y3-y4) - (y1-y2)*part2 63 | y/=d 64 | } 65 | 66 | pIntersectStartInv(Byref x, Byref y){ 67 | pIntersectStart(x,y) 68 | y := 400-y 69 | } 70 | 71 | realATan(x){ 72 | ; returns ATan() in range 0-180 degrees (0-pi radians) 73 | z := ATan(x) 74 | if (z<0) 75 | return PI2 + PI2 + z 76 | else 77 | return z 78 | } 79 | 80 | angleAtVertex(p1){ 81 | pc := p1 82 | pos := ObjhasValue(pc) 83 | pf := COORDS[pos + M] 84 | pb := COORDS[pos - M] 85 | return angleFromPoints(pb, pc, pf) 86 | } 87 | 88 | angleAtVertexALAS(v_id){ ; Aliases the effect of small slopes, makes use of vertices nicely 89 | if (v_id == 1) 90 | fp := COORDS[1] 91 | else 92 | fp := CORNS[v_id-1] 93 | if (v_id == CORNS.maxIndex()) 94 | lp := COORDS[COORDS.maxIndex()] 95 | else 96 | lp := CORNS[v_id+1] 97 | return angleFromPoints(fp, CORNS[v_id], lp) 98 | } 99 | 100 | angleFromPoints(pb, pc, pf){ 101 | vf := MakeVector(pc, pf) 102 | vb := MakeVector(pc, pb) 103 | return anglefromVector(vf, vb) 104 | } 105 | 106 | anglefromVector(vf, vb){ 107 | modside := ModVector(vf) * ModVector(vb) 108 | modfull := (vf[1]*vb[1]) + (vf[2]*vb[2]) 109 | costheta := modfull / modside 110 | costheta := costheta>1 ? 1 : (costheta<-1 ? -1 : costheta) 111 | return acos( costheta ) 112 | } 113 | 114 | ; validateAngle(a){ 115 | ; return a>ACC ? a : -100 116 | ; } 117 | 118 | calcSlope(p1, p2){ 119 | givePoints(p1, p1x, p1y) 120 | givePoints(p2, p2x, p2y) 121 | if (p1x == p2x) 122 | return "INF" 123 | else 124 | return (p2y-p1y)/(p2x-p1x) 125 | } 126 | 127 | MakeVector(p1, p2){ 128 | ; remember p1 is tail, p2 is head 129 | ; NOTE that coordinate axes are not same here - upper y is 0 lower is 400 130 | givePoints(p1, p1x, p1y) 131 | givePoints(p2, p2x, p2y) 132 | vx := p2x - p1x 133 | vy := p2y - p1y 134 | return {1: vx,2: vy} 135 | } 136 | 137 | MakeVectorCoords(x,y){ 138 | return {1: x, 2: y} 139 | } 140 | 141 | MakeUnitVector(v){ 142 | z := ModVector(v) 143 | return {1: (v[1]/z), 2: (v[2]/z)} 144 | } 145 | 146 | ModVector(v){ 147 | vx := v[1] 148 | vy := v[2] 149 | return sqrt( (vx*vx) + (vy*vy) ) 150 | } 151 | 152 | radToAngle(rad){ 153 | return rad * 180/PI 154 | } 155 | 156 | ObjhasValue(s){ 157 | for k,v in COORDS 158 | if (v==s) 159 | return k 160 | return 0 161 | } 162 | 163 | min(a,b){ 164 | return a>b ? b : a 165 | } 166 | max(a,b){ 167 | return a>b ? a : b 168 | } 169 | 170 | 171 | ;++++++++++++++++++++++++++++++++ 172 | ; I N I T D R A W I N G 173 | ;++++++++++++++++++++++++++++++++ 174 | 175 | initDrawing(){ 176 | PLT := ComObjCreate("GflAx.GflAx") 177 | if FileExist("i.bmp") 178 | PLT.LoadBitmap("i.bmp") 179 | else 180 | PLT.NewBitmap(400, 400) 181 | PLT.SaveFormatName := "bmp" 182 | PLT.LineWidth := PLT.LineWidth*2 183 | return PLT 184 | } -------------------------------------------------------------------------------- /lib/quad.ahk: -------------------------------------------------------------------------------- 1 | 2 | ; 2 is for square, 3 is for rectangle 3 | validateQuad(){ 4 | z := CORNS.MaxIndex() 5 | t := COORDS.MaxIndex() 6 | 7 | suc := 1, angle := 0 8 | for k,v in CORNS 9 | { 10 | a := angleAtVertexALAS(k) 11 | if (abs(a-PI2) > RANGLEACC) 12 | suc := 0 13 | angle += a 14 | } 15 | 16 | if (z==3){ 17 | a := anglefromVector( makeVector(COORDS[1], CORNS[1]) , MakeVector(COORDS[t], CORNS[3]) ) 18 | if (abs(a-PI2) > RANGLEACC) 19 | suc := 0 20 | angle += a 21 | } 22 | if (abs(angle-(PI*2)) > QUADACC) ; not even a qualidateral 23 | return -1 24 | else if (suc == 0) 25 | return ID_QUAD 26 | else 27 | return SquareOrRect() 28 | } 29 | 30 | 31 | SquareOrRect(){ 32 | ; in 3 vertex sq , the starting point will be the fourth point 33 | z := CORNS.MaxIndex() 34 | pIntersectStart(x0, y0) ; better to use this value 35 | COORDS[1] := x0 "-" y0 36 | if (z==4) 37 | s1 := distance(CORNS[4], CORNS[1]) 38 | else 39 | s1 := distance(COORDS[1], CORNS[1]) 40 | s2 := distance(CORNS[1], CORNS[2]) 41 | s3 := distance(CORNS[2], CORNS[3]) 42 | if (z!=4) 43 | s4 := distance(CORNS[3], COORDS[1]) 44 | else 45 | s4 := distance(CORNS[3], CORNS[4]) 46 | 47 | p1 := min(s1, s3) 48 | if (abs(s1-s3) > (QUADSIDEACC*p1)) 49 | return ID_QUAD 50 | p2 := min(s2, s4) 51 | if (abs(s2-s4) > (QUADSIDEACC*p2)) 52 | return ID_QUAD 53 | f := max(p1,p2) 54 | if (abs(p1-p2) <= (SQACC*f)) 55 | return drawQuad(1) 56 | else 57 | return drawQuad() 58 | } 59 | 60 | drawQuad(issq=0){ 61 | z := CORNS.maxIndex() 62 | ; TAKE POINTS (in order) 63 | /* 64 | p1---p4 65 | | | 66 | p2---p3 67 | */ 68 | p := Object() 69 | if (z==3){ 70 | pIntersectStart(x0, y0) 71 | p[1] := x0 "-" y0 72 | p[2] := CORNS[1] 73 | p[3] := CORNS[2] 74 | p[4] := CORNS[3] 75 | } 76 | else { 77 | p[1] := CORNS[1] 78 | p[2] := CORNS[2] 79 | p[3] := CORNS[3] 80 | p[4] := CORNS[4] 81 | } 82 | 83 | ; calc side lengths 84 | s1 := ( distance(p[1], p[2]) + distance(p[3], p[4]) ) / 2 85 | s2 := ( distance(p[2], p[3]) + distance(p[4], p[1]) ) / 2 86 | if (issq) 87 | s1 := (s1+s2)/2 , s2 := s1 88 | 89 | ; get ready for drawing 90 | plt := initDrawing() 91 | prev := "" 92 | p[5] := p[1] 93 | 94 | loop 4 95 | { 96 | if !IsObject(prev){ 97 | curv := makeUnitVector( makeVector(p[1], p[2]) ) 98 | } else { 99 | ; ax + by = 0 ; suppose x=1 100 | x := 1 101 | y := (-prev[1] * x) / prev[2] 102 | if (prev[2]==0) 103 | x := 0, y := 1 104 | curv := makeUnitVector( makeVectorCoords(x, y) ) 105 | } 106 | 107 | compv := makeVector(p[A_index], p[A_index+1]) 108 | curd := (Mod(A_index,2)==0) ? s2 : s1 109 | givePoints(p[A_Index], xc, yc) 110 | 111 | pset1 := (xc + curv[1]*curd) "-" (yc + curv[2]*curd) 112 | pset2 := (xc - curv[1]*curd) "-" (yc - curv[2]*curd) 113 | pset1v := MakeVector(p[A_Index], pset1) 114 | pset2v := MakeVector(p[A_index], pset2) 115 | 116 | pf := anglefromVector(pset1v, compv) < anglefromVector(pset2v, compv) ? pset1 : pset2 117 | givePointsInv(p[A_Index], ix0, iy0) 118 | givePointsInv(pf, ix1, iy1) 119 | plt.DrawLine(ix0, iy0, ix1, iy1) 120 | 121 | prev := curv.Clone() 122 | p[A_index+1] := pf 123 | } 124 | 125 | plt.SaveBitmap("i") 126 | ObjRelease(plt) 127 | return issq ? ID_SQ : ID_RECT 128 | } -------------------------------------------------------------------------------- /lib/triangle.ahk: -------------------------------------------------------------------------------- 1 | 2 | ; 1 is for triangle 3 | validateTriangle(){ 4 | z := CORNS.MaxIndex() 5 | t := COORDS.MaxIndex() 6 | angle := 0 7 | for k,v in CORNS 8 | angle += angleAtVertexALAS(k) 9 | 10 | if (z<3) 11 | angle += anglefromVector( makeVector(COORDS[1], CORNS[1]) , makeVector(COORDS[t], CORNS[2]) ) 12 | 13 | if ( Abs(angle-PI) < TRIACC ) 14 | return drawTriangle() 15 | else return -1 16 | } 17 | 18 | drawTriangle(){ 19 | PLT := initDrawing() 20 | 21 | z := CORNS.maxIndex() 22 | givePointsInv(CORNS[1], x1, y1) 23 | givePointsInv(CORNS[2], x2, y2) 24 | if (z==3) 25 | givePointsInv(CORNS[3], x3, y3) 26 | else 27 | pIntersectStartInv(x0, y0) 28 | 29 | if (z==3){ 30 | PLT.DrawLine(x2, y2, x1, y1) 31 | PLT.DrawLine(x3, y3, x2, y2) 32 | PLT.DrawLine(x3, y3, x1, y1) 33 | } 34 | else{ 35 | PLT.DrawLine(x0, y0, x1, y1) 36 | PLT.DrawLine(x1, y1, x2, y2) 37 | PLT.DrawLine(x2, y2, x0, y0) 38 | } 39 | PLT.SaveBitmap("i") 40 | ObjRelease(PLT) 41 | return ID_TRI 42 | } -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Shape Recog 2 | 3 | Shape Recog is a figure analyzer and synthesizer. It scans a drawn figure and checks if it's square, rectangle, triangle, circle, line or INVALID. After analyzing a figure, 4 | it then redraws the perfect representation of that figure. 5 | 6 | ### Screenshot 7 | 8 | [http://s21.postimg.org/frlupx2mf/rec.gif](http://s21.postimg.org/frlupx2mf/rec.gif) 9 | ![GIF](http://s21.postimg.org/frlupx2mf/rec.gif) 10 | 11 | 12 | ### How it was done 13 | 14 | * Main Aim was to detect vertices of the figure 15 | * If vertices are infinite (or 0), then it is a circle. - If vertices are 2 or 3, then it is a triangle. If vertices are 3 or 4, then it is a quadrilateral. 16 | * Now to detect vertices, we take points in order and take slopes with respect to [point+10] and [point-10]th point. If slopes differ by a threshold angle (20), then that's a vertex. 17 | * But here's the problem. The threshold approach will give many points near to each other as vertex because of the above method. 18 | * So we calculate mean of all the points in one family and take that as vertex. 19 | * 3 vertexe'd figures can be either triangle or quadrilateral. But in triangle the backward slope of first vertex and forward slope of last vertex are same. So that separates 20 | it from the quadrilateral. 21 | * For quadrilaterals with 3-vertex, the fourth vertex will essentially be the starting point. 22 | * Circles and Lines are both 0-vertex figures but in CIRCLE the ratio of `potential_vertices/total_points` is close to 1 and in line its close to 0. 23 | * Now the next aim is to detect the angles between edges. Angles will help greatly in removing figures that are actually not like the detected geometric figures. 24 | * Creating **Directional Vectors** of coords can help to get the correct angle between 2 edges. Dot (Scalar) Product can help. 25 | * Now when we have angles, we can validate if a figure is a correct triangle/square/rectangle or not. 26 | * Calculating angles for polygons is much better when angle is calculated with help of adjacent vertices. This way we get the best approximated figure. 27 | * Now to validate if figures drawn are closed and symbolically correct, we can use the fact that distance(last_point, first_point) should always be less than 28 | distance(last_vertex, first_point). Cases which violate this test should be caught in the *Angle Test*. 29 | * We are also using the [Distance Formula](http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points) to check if a figure will actually close or tend to close. 30 | * To validate circles, we calculate the Horizontal Diameter and the Vertical Diameter and compare them. We also check if co-ordinates for these diameters are aligned or not. If the co-ordinates are aligned but diameters are different, the figure is an *oval*. 31 | * For further validating polygons, we check if lines drawn from vertex to vertex are straight or not. We will use the Distance Formula to check for the drawn line's difference with the ideal line. 32 | * We also check if the figure is closing or not. If the last line completes 70% of length of what is should have done, then fine else figure will be shown as INVALID. Again this 33 | 70 is just a random appropriate figure and there's no mathematical proof of why it is used. 34 | * For figuring out whether Square or Rectangle, side lengths are sufficient. As this is done after all those checks for quadrilateral, just testing the length works fine. 35 | * Vertices detected very close to each other are settled to one. This is done as many people tremble around the vertex region. 36 | * There is no need for lines to differ by the threshold angle (20) as it is very large. After a line is detected, we re-check it with threshold angle of 5 to see if it's really a line. 37 | * For incomplete polygons (2-Triangle, 3-Rectangle), user will expect the intersection point to be a vertex. This fact is used in drawing to provide a more-expected correction. 38 | * Drawing Squares and Rectangles was a challenging task as you have to make sure both edge length and angles are according to specifications. In here, we first determine the average length of a side and choose a vertex. Then we continue making sides perpendicular to the previous side and with proper edge length. Concept of Vectors play a huge role in making this possible. 39 | * A big problem was that vertices were detected in slow-drawn circles. So we force-check for circle in case of INVALID detection and draw a circle if found. A force-check uses a brute force method where diameters and centers for each point on the circumfrence are calculated. Diameter is the farthest point away from it and center is the mid-point of diameter. Average of diameters and centers give a pretty exact value. 40 | 41 | 42 | ### What we learned from this project 43 | 44 | * The correct spelling of *qualidateral*. -------------------------------------------------------------------------------- /shape_recog.ahk: -------------------------------------------------------------------------------- 1 | /* 2 | ShapeRecog 3 | 4 | Copyright 2015 Avi Aryan 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | */ 18 | 19 | /* 20 | REFERNCES 21 | 22 | InkPicture - https://msdn.microsoft.com/en-us/library/windows/desktop/ms704450%28v=vs.85%29.aspx 23 | */ 24 | 25 | 26 | 27 | SetWorkingDir, % A_ScriptDir 28 | SetBatchlines, -1 29 | #NoEnv 30 | #SingleInstance, force 31 | OnExit, end_it_all 32 | RunWait, regsvr32.exe /s "%A_scriptdir%\GflAx.dll" 33 | FileDelete, % "i.bmp" 34 | 35 | ;-------------------- 36 | ; G L O B A L S 37 | ;-------------------- 38 | 39 | global PROGNAME := "Shape Recog" 40 | global PI := asin(1)*2 41 | global PI2 := asin(1) 42 | global drawspace, logs, prev_point := "600-600" 43 | global COORDS = Object(), COORDScpy 44 | global CORNS = Object() 45 | global ID_LINE := 0, ID_TRI := 1, ID_SQ := 2, ID_RECT = 3, ID_CIR := 4, ID_QUAD := -2, ID_DIST := -3, ID_OVAL := -4 46 | global PXL, PXR, PYT, PYB, PYL, PYR, PXT, PXB, FIGSZ, FIGSZSMALL 47 | global FVERTEXCT 48 | 49 | ;--------------------- 50 | ; S E T T I N G S 51 | ;--------------------- 52 | 53 | global MSLOPE := 10, MSLOPELL := 3, M, LMT 54 | global DIST_APART := 0.5 55 | global ACC = 20*PI/180 56 | 57 | global TRIACC := 30*PI/180 58 | 59 | global RANGLEACC := 20*PI/180 60 | global QUADACC := 60*PI/180 ; not possible that everywhere you make>90 so a lower value whould work 61 | global QUADSIDEACC := 0.3 62 | global SQACC := 0.2 63 | 64 | global CIRCACC := 0.5 65 | global CIRC_DIST_APART := 0.3 66 | ; division factor of distance curve can be away from the line 67 | global LINE_DIST_F := 4 68 | 69 | 70 | ;-------------------- 71 | ; L A S T S T E P S 72 | ;-------------------- 73 | 74 | makeGUI() 75 | Return 76 | 77 | ;---------------------- 78 | ; S H A P E D E T E C T I O N 79 | ;---------------------- 80 | 81 | detectCorners(){ 82 | len := COORDS.maxIndex() 83 | boundaries() 84 | CORNS := {} 85 | FVERTEXCT := 0 86 | 87 | M := MSLOPE 88 | if (len < 100) 89 | M := round( M * (len/100.0) ) 90 | if (MM){ 101 | cur := calcSlope( COORDS[A_index], COORDS[A_index-M] ) 102 | pre := calcSlope( COORDS[A_index+M], COORDS[A_index] ) 103 | 104 | Z := calcAngle(pre, cur) 105 | 106 | if ( Z > ACC ){ 107 | tobj.Insert(COORDS[A_Index]) 108 | ST := 1 109 | FVERTEXCT++ 110 | } else { 111 | if (ST){ 112 | if ( (TOBJ.MaxIndex() > 2) && (TOBJ.MaxIndex() < LMT) ) 113 | CORNS.Insert( TOBJ[ Round(TOBJ.maxIndex()/2) ] ) 114 | } 115 | tobj := {} 116 | ST := 0 117 | } 118 | } 119 | } 120 | 121 | if (ST){ 122 | if ( (TOBJ.MaxIndex() > 2) && (TOBJ.MaxIndex() < LMT) ) 123 | CORNS.Insert( TOBJ[ Round(TOBJ.maxIndex()/2) ] ) 124 | } 125 | 126 | validateCorners() 127 | } 128 | 129 | validateCorners(){ 130 | f := CORNS[1] 131 | z := CORNS.maxIndex() 132 | loop % z-1 133 | { 134 | if (distance(CORNS[A_index+1], f) < (FIGSZSMALL/10)){ 135 | CORNS.Remove(A_index+1) 136 | f := CORNS[A_index] 137 | } else 138 | f := CORNS[A_index+1] 139 | } 140 | } 141 | 142 | detectShape(){ 143 | /* 144 | 0 = LINE 145 | 1 = TRIANGLE 146 | 2 = SQUARE 147 | 3 = RECTANGLE 148 | 4 = CIRCLE 149 | */ 150 | k := CORNS.MaxIndex() 151 | if (!k){ 152 | x := circleOrLine() 153 | if (x==ID_CIR) 154 | return validateCircle() 155 | else return x 156 | } 157 | else if (k==1) 158 | return -1 ;validateCircle() 159 | ; now after LINE is resolved, validate figure 160 | if ( (P:=validatePolygonFigure())<1 ) 161 | return P 162 | if (k == 2) 163 | return validateTriangle() 164 | else if (k == 3){ 165 | z := quadOrTriangle() 166 | if (z==ID_TRI) 167 | return validateTriangle() 168 | else if (z != -1) 169 | return validateQuad() 170 | } else if (k == 4) 171 | return validateQuad() 172 | else 173 | return -1 174 | } 175 | 176 | quadOrTriangle(){ 177 | static A22 := asin(1)/4 178 | static NINETYACC := PI2 - RANGLEACC 179 | fslope := calcSlope(CORNS[1], COORDS[1]) 180 | lslope := calcSlope(COORDS[COORDS.maxIndex()], CORNS[3]) 181 | 182 | if (calcAngle(lslope, fslope) < A22) 183 | return ID_TRI 184 | else if (calcAngle(lslope, fslope) > NINETYACC) 185 | return ID_RECT 186 | else 187 | return ID_RECT ; validateQUAD() will figure this out 188 | } 189 | 190 | circleOrLine(){ 191 | percent := FVERTEXCT / (COORDS.maxIndex()-2*M) 192 | if (percent > 0.7) ; generally this is seen 193 | return ID_CIR 194 | else if (percent < 0.2) 195 | return validateLine() ;ID_LINE 196 | else 197 | return -1 198 | } 199 | 200 | validatePolygonFigure(){ 201 | ; figure closing 202 | lp := CORNS[CORNS.maxIndex()] 203 | fp := COORDS[1] 204 | x := distance(lp, fp) 205 | if (distance(COORDS[COORDS.maxIndex()], fp) > (DIST_APART*x)) 206 | return ID_DIST 207 | 208 | ; last line closes to starting point 209 | ; http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points 210 | p2 := COORDS[COORDS.maxIndex()] 211 | p1 := CORNS[CORNS.maxIndex()] 212 | givePoints(p2, p2x, p2y) 213 | givePoints(p1, p1x, p1y) 214 | givePoints(COORDS[1], p0x, p0y) 215 | num := abs( (p2y-p1y)*p0x - (p2x-p1x)*p0y + (p2x*p1y-p2y*p1x) ) 216 | den := sqrt( (p2y-p1y)**2 + (p2x-p1x)**2 ) 217 | z := num/den 218 | if ( z > (DIST_APART*FIGSZ) ) 219 | return ID_DIST 220 | 221 | ; check IF vector last is pointing in right direction 222 | lastp := distance(COORDS[1], p2) 223 | slastp := distance(COORDS[1], p1) 224 | if (slastp < lastp) 225 | return -1 226 | 227 | ; edge dedication 228 | ; let tolerance depend on line length 229 | z := CORNS.maxIndex() 230 | loop % z+1 231 | { 232 | v := CORNS[A_Index] 233 | lp := v 234 | fp := CORNS[A_index-1] 235 | if (A_index == 1) 236 | fp := COORDS[1] 237 | if (A_index>z) 238 | lp := COORDS[COORDS.maxIndex()] 239 | dist := distance(lp, fp)/LINE_DIST_F 240 | givePoints(lp, p2x, p2y) 241 | givePoints(fp, p1x, p1y) 242 | startp := ObjhasValue(fp) 243 | endp := ObjhasValue(lp) 244 | times := endp-startp+1 245 | loop % times 246 | { 247 | curp := COORDS[startp] 248 | givePoints(curp, p0x, p0y) 249 | num := abs( (p2y-p1y)*p0x - (p2x-p1x)*p0y + (p2x*p1y-p2y*p1x) ) 250 | den := sqrt( (p2y-p1y)**2 + (p2x-p1x)**2 ) 251 | zc := num/den 252 | if (zc>dist) 253 | return -1 254 | startp++ 255 | } 256 | } 257 | 258 | return 1 259 | } 260 | 261 | calcAngle(slope1, slope2){ 262 | 263 | if (slope2 == "INF"){ 264 | if (slope1 != "INF") 265 | Z := abs( PI2 - atan(slope1) ) 266 | else Z := 0.000 267 | } else if (slope1 == "INF"){ 268 | Z := abs(PI2-atan(slope2)) 269 | } else 270 | Z := abs( atan( (slope2 - slope1) / (1 + slope2*slope1) ) ) 271 | 272 | if (Z>PI2) ; obtuse angle 273 | { 274 | Z := PI - Z ; comes in INF case 275 | } 276 | return Z 277 | } 278 | 279 | boundaries(){ 280 | PXL := 401 281 | PXR := 0 282 | PYT := 0 283 | PYB := 401 284 | for k,v in COORDS 285 | { 286 | givePoints(v, tx, ty) 287 | if (txPXR) 290 | PXR := tx, PYR := ty 291 | if (ty>PYT) 292 | PYT := ty, PXT := tx 293 | if (ty-1) 365 | showMsg("Force-checking circle successful") 366 | } 367 | showMsg("Shape Detected As : " resolveShapeId(x)) 368 | if (x>-1) 369 | GuiControl,, output, % "i.bmp" 370 | } 371 | 372 | showMsg(msg){ 373 | Gui, 1:submit, NoHide 374 | GuiControlGet, logs 375 | GuiControl,, logs, % logs "`n" msg 376 | ControlSend, Edit1, ^{End}, % PROGNAME " ahk_class AutoHotkeyGUI" 377 | } 378 | 379 | class drawspace_events { 380 | MouseMove(button, shift, px, py, cancel){ 381 | if (GetKeyState("LButton", "P")){ 382 | py := 400-py ; invert that m** 383 | if ( ObjhasValue(px "-" py) == 0 ) 384 | ;if (distance(px "-" py, prev_point) > 3){ 385 | COORDS.Insert(px "-" py) 386 | ; prev_point := px "-" py 387 | ;} 388 | } 389 | } 390 | 391 | Stroke(cursor, stroke, cancel){ ; after a stroke is drawn 392 | detect() 393 | COORDS := {} 394 | prev_point := "600-600" 395 | } 396 | } 397 | 398 | 399 | 400 | end_it_all: 401 | drawspace := "" 402 | RunWait, regsvr32.exe /u /s "%A_scriptdir%/Gflax.dll" 403 | FileDelete, % "i.bmp" 404 | ExitApp 405 | return 406 | 407 | ;-------------------------------- 408 | ; I N C L U D E S 409 | ;-------------------------------- 410 | 411 | #include lib\misc.ahk 412 | #include lib\triangle.ahk 413 | #include lib\quad.ahk 414 | #include lib\circle.ahk -------------------------------------------------------------------------------- /shape_recog.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aviaryan/shape-recog/08793ccbd5a915152021e6e14a21ed5e78e81741/shape_recog.exe --------------------------------------------------------------------------------