1+ # -*- coding: utf-8 -*-
2+ import math
3+ import numpy as np
4+ from PIL import Image
5+ from skimage .draw import line
6+
7+ from .LineDictionary import LineDictionary
8+ import cv2
9+
10+ lineLengths = [3 ,5 ,7 ,9 ]
11+ lineTypes = ["full" , "right" , "left" ]
12+
13+ lineDict = LineDictionary ()
14+
15+ def LinearMotionBlur_random (img ):
16+ lineLengthIdx = np .random .randint (0 , len (lineLengths ))
17+ lineTypeIdx = np .random .randint (0 , len (lineTypes ))
18+ lineLength = lineLengths [lineLengthIdx ]
19+ lineType = lineTypes [lineTypeIdx ]
20+ lineAngle = randomAngle (lineLength )
21+ return LinearMotionBlur (img , lineLength , lineAngle , lineType )
22+
23+ def LinearMotionBlur (img , dim , angle , linetype ):
24+ imgarray = np .array (img , dtype = "float32" )
25+ kernel = LineKernel (dim , angle , linetype )
26+ convolved = cv2 .filter2D (imgarray , - 1 , kernel ).astype ("uint8" )
27+ img = Image .fromarray (convolved )
28+ return img
29+
30+ def LineKernel (dim , angle , linetype ):
31+ kernelwidth = dim
32+ kernelCenter = int (math .floor (dim / 2 ))
33+ angle = SanitizeAngleValue (kernelCenter , angle )
34+ kernel = np .zeros ((kernelwidth , kernelwidth ), dtype = np .float32 )
35+ lineAnchors = lineDict .lines [dim ][angle ]
36+ if (linetype == 'right' ):
37+ lineAnchors [0 ] = kernelCenter
38+ lineAnchors [1 ] = kernelCenter
39+ if (linetype == 'left' ):
40+ lineAnchors [2 ] = kernelCenter
41+ lineAnchors [3 ] = kernelCenter
42+ rr ,cc = line (lineAnchors [0 ], lineAnchors [1 ], lineAnchors [2 ], lineAnchors [3 ])
43+ kernel [rr ,cc ]= 1
44+ normalizationFactor = np .count_nonzero (kernel )
45+ kernel = kernel / normalizationFactor
46+ return kernel
47+
48+ def SanitizeAngleValue (kernelCenter , angle ):
49+ numDistinctLines = kernelCenter * 4
50+ angle = math .fmod (angle , 180.0 )
51+ validLineAngles = np .linspace (0 ,180 , numDistinctLines , endpoint = False )
52+ angle = nearestValue (angle , validLineAngles )
53+ return angle
54+
55+ def nearestValue (theta , validAngles ):
56+ idx = (np .abs (validAngles - theta )).argmin ()
57+ return validAngles [idx ]
58+
59+ def randomAngle (kerneldim ):
60+ kernelCenter = int (math .floor (kerneldim / 2 ))
61+ numDistinctLines = kernelCenter * 4
62+ validLineAngles = np .linspace (0 ,180 , numDistinctLines , endpoint = False )
63+ angleIdx = np .random .randint (0 , len (validLineAngles ))
64+ return int (validLineAngles [angleIdx ])
0 commit comments