def augmentate(self):
angles = [45, 90, 135, 180, 225, 270, 315]
scale = 1.0
for img in self.images:
print "image shape : ", img.shape
w = img.shape[1]
h = img.shape[0]
img_vmirror = cv2.flip(img,1)
skimage.io.imsave("testv"+".jpg", img_vmirror )
for angle in angles:
#rangle = np.deg2rad(angle)
# nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale
# nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale
rot_mat = cv2.getRotationMatrix2D((w*0.5, h*0.5), angle, scale)
# rot_move = np.dot(rot_mat, np.array([(nw-w)*0.5, (nh-h)*0.5,0]))
# rot_mat[0,2] += rot_move[0]
# rot_mat[1,2] += rot_move[1]
new_img = cv2.warpAffine(img, rot_mat, (int(math.ceil(w)), int(math.ceil(h))), flags=cv2.INTER_LANCZOS4)
skimage.io.imsave("test"+str(angle)+".jpg", new_img)
new_img_vmirror = cv2.flip(new_img, 1)
skimage.io.imsave("testv"+str(angle)+".jpg", new_img_vmirror)
# img_rmirror = cv2.flip(new_img, 0)
# skimage.io.imsave("testh"+str(angle)+".jpg", img_rmirror)
python类deg2rad()的实例源码
def sphericalToXYZ(lat,lon,radius=1):
'''
Convert spherical coordinates to x,y,z
@param lat: Latitude, scalar or array
@param lon: Longitude, scalar or array
@param radius: Sphere's radius
@return Numpy array of x,y,z coordinates
'''
phi = np.deg2rad(90.0 - lat)
theta = np.deg2rad(lon % 360)
x = radius * np.cos(theta)*np.sin(phi)
y = radius * np.sin(theta)*np.sin(phi)
z = radius * np.cos(phi)
if np.isscalar(x) == False:
return np.vstack([x,y,z]).T
else:
return np.array([x,y,z])
def plot_chara(self, angle, step,Rstar = 1):
counter = 1000
i = np.arange(counter)
Rstar_tmp = self.Rstar_min + i / counter
Rstar_tmp = Rstar_tmp[Rstar_tmp < 1]
fai = self.chara_line(Rstar_tmp)
for j in range(0, angle, step):
x1 = self.chara_x(Rstar_tmp * Rstar, fai - self.const + np.deg2rad(j))
y1 = self.chara_y(Rstar_tmp * Rstar, fai - self.const + np.deg2rad(j))
x2 = self.chara_x(Rstar_tmp * Rstar, - (fai - self.const - np.deg2rad(j)))
y2 = self.chara_y(Rstar_tmp * Rstar, - (fai - self.const - np.deg2rad(j)))
plt.plot(x1, y1, "r")
plt.plot(x2, y2, "k")
plt.xlim(-1, 1)
plt.ylim(-1, 1)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
# top arc angle is 0
# v1 must be smaller than v2
def make_upper_straight_line(self):
""" make upper straight line """
targetx = self.lower_concave_in_x_end
x = self.upper_convex_in_x_end
y = self.upper_convex_in_y_end
targety = np.tan(np.deg2rad(self.beta_in)) * targetx + y - np.tan(np.deg2rad(self.beta_in)) * x
self.upper_straight_in_x = [targetx, x]
self.upper_straight_in_y = [targety, y]
self.shift = - abs(self.lower_concave_in_y_end - targety)
targetx = self.lower_concave_out_x_end
x = self.upper_convex_out_x_end
y = self.upper_convex_out_y_end
targety = np.tan(np.deg2rad(self.beta_out)) * targetx + y - np.tan(np.deg2rad(self.beta_out)) * x
self.upper_straight_out_x = [targetx, x]
self.upper_straight_out_y = [targety, y]
image_processing_common.py 文件源码
项目:tensorflow-litterbox
作者: rwightman
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def distort_affine_skimage(image, rotation=10.0, shear=5.0, random_state=None):
if random_state is None:
random_state = np.random.RandomState(None)
rot = np.deg2rad(np.random.uniform(-rotation, rotation))
sheer = np.deg2rad(np.random.uniform(-shear, shear))
shape = image.shape
shape_size = shape[:2]
center = np.float32(shape_size) / 2. - 0.5
pre = transform.SimilarityTransform(translation=-center)
affine = transform.AffineTransform(rotation=rot, shear=sheer, translation=center)
tform = pre + affine
distorted_image = transform.warp(image, tform.params, mode='reflect')
return distorted_image.astype(np.float32)
def __init__(self, fig, variables, ranges, n_ordinate_levels=6):
angles = np.arange(0, 360, 360./len(variables))
axes = [fig.add_axes([0,0, 1,1],polar=True,
label = "axes{}".format(i))
for i in range(len(variables))]
l, text = axes[0].set_thetagrids(angles, labels = variables)
[txt.set_rotation(angle-90) for txt, angle in zip(text, angles)]
for ax in axes[1:]:
ax.patch.set_visible(False)
ax.grid("off")
ax.xaxis.set_visible(False)
for i, ax in enumerate(axes):
grid = np.linspace(*ranges[i], num=n_ordinate_levels)
gridlabel = ["{}".format(round(x,2)) for x in grid]
if ranges[i][0] > ranges[i][1]:
grid = grid[::-1] # hack to invert grid
# gridlabels aren't reversed
gridlabel[0] = "" # clean up origin
ax.set_rgrids(grid, labels=gridlabel, angle=angles[i])
ax.set_ylim(*ranges[i])
# variables for plotting
self.angle = np.deg2rad(np.r_[angles, angles[0]])
self.ranges = ranges
self.ax = axes[0]
def generate_circle_points(radius, initial_angle, final_angle, points=199):
"""
This methods generates points in a circle shape at (0,0) with a specific radius and from a
starting angle to a final angle.
Args:
radius: radius of the circle in microns
initial_angle: initial angle of the drawing in degrees
final_angle: final angle of the drawing in degrees
points: amount of points to be generated (default 199)
Returns:
Set of points that form the circle
"""
theta = np.linspace( np.deg2rad(initial_angle),
np.deg2rad(final_angle),
points)
return radius * np.cos(theta) , radius * np.sin(theta)
def disttoedge(self, x, y, d):
rd = numpy.deg2rad(d)
dx, dy = numpy.cos(rd), numpy.sin(rd)
maxx = self.width()
maxy = self.height()
if dx == 0:
lefthit, righthit = sys.maxsize, sys.maxsize
tophit, bothit = (maxy - y) / dy, (-y) / dy
elif dy == 0:
lefthit, righthit = (-x) / dx, (maxx - x) / dx
tophit, bothit = sys.maxsize, sys.maxsize
else:
lefthit, righthit = (-x) / dx, (maxx - x) / dx
tophit, bothit = (maxy - y) / dy, (-y) / dy
# Return smallest positive
dists = list(filter(lambda s: s > 0, [lefthit, righthit, tophit, bothit]))
if len(dists) == 0:
return 0
else:
return min(dists)
def rotation_matrix_axis(C_values):
# Change coordinate system through matrix C
rx = np.deg2rad(float(C_values[0]))
ry = np.deg2rad(float(C_values[1]))
rz = np.deg2rad(float(C_values[2]))
Cx = np.matrix([[1, 0, 0],
[0, np.cos(rx), np.sin(rx)],
[0, -np.sin(rx), np.cos(rx)]])
Cy = np.matrix([[np.cos(ry), 0, -np.sin(ry)],
[0, 1, 0],
[np.sin(ry), 0, np.cos(ry)]])
Cz = np.matrix([[np.cos(rz), np.sin(rz), 0],
[-np.sin(rz), np.cos(rz), 0],
[0, 0, 1]])
C = Cx * Cy * Cz
Cinv = np.linalg.inv(C)
return C, Cinv
def rotation_matrix(bone, tx, ty, tz):
# Construct rotation matrix M
tx = np.deg2rad(tx)
ty = np.deg2rad(ty)
tz = np.deg2rad(tz)
Mx = np.matrix([[1, 0, 0],
[0, np.cos(tx), np.sin(tx)],
[0, -np.sin(tx), np.cos(tx)]])
My = np.matrix([[np.cos(ty), 0, -np.sin(ty)],
[0, 1, 0],
[np.sin(ty), 0, np.cos(ty)]])
Mz = np.matrix([[np.cos(tz), np.sin(tz), 0],
[-np.sin(tz), np.cos(tz), 0],
[0, 0, 1]])
M = Mx * My * Mz
L = bone.Cinv * M * bone.C
return L
def keyframedb(self, theta=np.deg2rad(20), displacement=0.25, lookup_history=10, verbose=True):
sampler = PoseSampler(theta=theta, displacement=displacement, lookup_history=lookup_history,
get_sample=lambda (t, channel, frame): frame.pose, verbose=verbose)
self.iterframes = partial(sampler.iteritems, self.iterframes())
return self
# def list_annotations(self, target_name=None):
# " List of lists"
# inds = self.annotated_inds
# return [ filter(lambda frame:
# target_name is None or name is in target_name,
# self.dataset.annotationdb.iterframes(inds))
# def _build_graph(self):
# # Keep a queue of finite length to ensure
# # time-sync with RGB and IMU
# self.__pose_q = deque(maxlen=10)
# self.nodes_ = []
# for (t,ch,data) in self.dataset_.itercursors(topics=[]):
# if ch == TANGO_VIO_CHANNEL:
# self.__pose_q.append(data)
# continue
# if not len(self.__pose_q):
# continue
# assert(ch == TANGO_RGB_CHANNEL)
# self.nodes_.append(dict(img=data, pose=self.__pose_q[-1]))
# Basic type for tango frame (includes pose, image, timestamp)
def draw_camera(pose, zmin=0.0, zmax=0.1, fov=np.deg2rad(60)):
frustum = Frustum(pose, zmin=zmin, zmax=zmax, fov=fov)
nul, nll, nlr, nur, ful, fll, flr, fur = frustum.vertices
# nll, nlr, nur, nul, fll, flr, fur, ful = frustum.vertices
faces = []
# Triangles: Front Face
faces.extend([ful, fur, flr])
faces.extend([flr, ful, fll])
# Triangles: Back Face
faces.extend([nul, nur, nlr])
faces.extend([nlr, nul, nll])
# Triangles: Four walls (2-triangles per face)
left, top, right, bottom = [fll, nll, ful, ful, nll, nul], \
[ful, nul, fur, fur, nul, nur], \
[fur, nur, flr, flr, nur, nlr], \
[flr, nlr, fll, fll, nlr, nll]
faces.extend([left, top, right, bottom]) # left, top, right, bottom wall
faces = np.vstack(faces)
# Lines: zmin-zmax
pts = []
pts.extend([ful, fur, flr, fll, ful])
pts.extend([ful, fll, nll, nul, ful])
pts.extend([ful, nul, nur, fur, ful])
pts.extend([fur, nur, nlr, flr, fur])
pts.extend([flr, nlr, nll, fll, flr])
pts = np.vstack(pts)
return (faces, np.hstack([pts[:-1], pts[1:]]).reshape((-1,3)))
def __init__(self, pose, zmin=0.0, zmax=0.1, fov=np.deg2rad(60)):
# FoV derived from fx,fy,cx,cy=500,500,320,240
# fovx, fovy = 65.23848614 51.28201165
rx, ry = 0.638, 0.478
self.pose = pose
arr = [np.array([-rx, -ry, 1.]) * zmin,
np.array([-rx, ry, 1.]) * zmin,
np.array([ rx, ry, 1.]) * zmin,
np.array([ rx, -ry, 1.]) * zmin,
np.array([-rx, -ry, 1.]) * zmax,
np.array([-rx, ry, 1.]) * zmax,
np.array([ rx, ry, 1.]) * zmax,
np.array([ rx, -ry, 1.]) * zmax]
# vertices: nul, nll, nlr, nur, ful, fll, flr, fur
self.vertices_ = self.pose * np.vstack(arr)
# self.near, self.far = np.array([0,0,zmin]), np.array([0,0,zmax])
# self.near_off, self.far_off = np.tan(fov / 2) * zmin, np.tan(fov / 2) * zmax
# arr = [self.near + np.array([-1, -1, 0]) * self.near_off,
# self.near + np.array([1, -1, 0]) * self.near_off,
# self.near + np.array([1, 1, 0]) * self.near_off,
# self.near + np.array([-1, 1, 0]) * self.near_off,
# self.far + np.array([-1, -1, 0]) * self.far_off,
# self.far + np.array([1, -1, 0]) * self.far_off,
# self.far + np.array([1, 1, 0]) * self.far_off,
# self.far + np.array([-1, 1, 0]) * self.far_off]
# nll, nlr, nur, nul, fll, flr, fur, ful = self.pose * np.vstack(arr)
# return nll, nlr, nur, nul, fll, flr, fur, ful
def __init__(self, theta=np.deg2rad(20), displacement=0.25, lookup_history=10,
get_sample=lambda item: item,
on_sampled_cb=lambda index, item: None, verbose=False):
Sampler.__init__(self, lookup_history=lookup_history,
get_sample=get_sample,
on_sampled_cb=on_sampled_cb, verbose=verbose)
self.displacement_ = displacement
self.theta_ = theta
def obj_set_position_target(self, handle, angle):
return self.RAPI_rc(vrep.simxSetJointTargetPosition( self.cID,handle,
-np.deg2rad(angle),
vrep.simx_opmode_blocking))
def getJitteredParams(self, num, center=(0.0, 0.0), maxRot=(-5.0, 5.0), maxTranslate=(-2.0, 2.0),
maxScale=(-0.1, 0.1), mirror=True):
if not (type(maxRot) is tuple):
maxRot = (-maxRot, maxRot)
if not (type(maxTranslate) is tuple):
maxTranslate = (-maxTranslate, maxTranslate)
if not (type(maxScale) is tuple):
maxScale = (-maxScale, maxScale)
alphas = self.rng.rand(num) * (maxRot[1] - maxRot[0]) + maxRot[0]
alphas = numpy.deg2rad(alphas)
tx = self.rng.rand(num) * (maxTranslate[1] - maxTranslate[0]) + maxTranslate[0]
ty = self.rng.rand(num) * (maxTranslate[1] - maxTranslate[0]) + maxTranslate[0]
sc = 2 ** -(self.rng.rand(num) * (maxScale[1] - maxScale[0]) + maxScale[0])
if mirror:
mi = self.rng.randint(2, size=num) # mirror true or false
else:
mi = numpy.zeros(num)
transformationMats = []
for i in range(num):
# First is not modified
if i == 0:
t = numpy.array([0, 0, 0, 1, 0])
else:
t = numpy.array([alphas[i], tx[i], ty[i], sc[i], mi[i]])
transformationMats.append(t)
return transformationMats
def rotate(self, deg, center = (0,0)):
''' rotates the image by set degree'''
#where c is the cosine of the angle, s is the sine of the angle and
#x0, y0 are used to correctly translate the rotated image.
# size of source image
src_dimsx = self.data.shape[0]
src_dimsy = self.data.shape[1]
# get the radians and calculate sin and cos
rad = np.deg2rad(deg)
c = np.cos(rad)
s = np.sin(rad)
# calculate center of image
cx = center[0] + src_dimsx/2
cy = center[1] + src_dimsy/2
# factor that moves the index to the center
x0 = cx - c*cx - s*cx
y0 = cy - c*cy + s*cy
# initialize destination image
dest = MyImage(self.data.shape)
for y in range(src_dimsy):
for x in range(src_dimsx):
# get the source indexes
src_x = int(c*x + s*y + x0)
src_y = int(-s*x + c*y + y0)
if src_y > 0 and src_y < src_dimsy and src_x > 0 and src_x < src_dimsx:
#paste the value in the destination image
dest.data[x][y] = self.data[src_x][src_y]
self.data = dest.data
def normalize_cord(latitude, longitude):
'''
Normalize GPS cord array, assuming the earth is shpherical
:param latitude: latitude array to normalize
:param longitude: longitude array to normalize
:return: normalized arrays (np.array)
'''
rad_lat = np.deg2rad(latitude)
rad_lon = np.deg2rad(longitude)
x = np.cos(rad_lat) * np.cos(rad_lon)
y = np.cos(rad_lat) * np.sin(rad_lon)
z = np.sin(rad_lat)
return x, y, z
def d_xy(self):
"""
The sampling interval along the (X, Y) spatial dimensions,
translated from the pixel size.
Unit: [Mpc]
Reference: Ref.[liu2014].Eq.(A7)
"""
pixelsize = self.pixelsize / 3600 # [arcsec] -> [deg]
d_xy = self.DMz * np.deg2rad(pixelsize)
return d_xy
def rotate_about_center(src, angle, scale=1.):
w = src.shape[1]
h = src.shape[0]
rangle = np.deg2rad(angle) # angle in radians
nw = (abs(np.sin(rangle)*h) + abs(np.cos(rangle)*w))*scale
nh = (abs(np.cos(rangle)*h) + abs(np.sin(rangle)*w))*scale
rot_mat = cv2.getRotationMatrix2D((nw*0.5, nh*0.5), angle, scale)
rot_move = np.dot(rot_mat, np.array([(nw-w)*0.5, (nh-h)*0.5,0]))
rot_mat[0,2] += rot_move[0]
rot_mat[1,2] += rot_move[1]
return cv2.warpAffine(src, rot_mat, (int(math.ceil(nw)), int(math.ceil(nh))), flags=cv2.INTER_LANCZOS4)