Jupyter Demo - Ipynb - Colaboratory

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

import numpy as np

np.pi

3.141592653589793

help(np)
trunc(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Return the truncated value of the input, element-wise.

The truncated value of the scalar `x` is the nearest integer `i` which
is closer to zero than `x` is. In short, the fractional part of the
signed number `x` is discarded.

Parameters
----------
x : array_like
Input data.
out : ndarray, None, or tuple of ndarray and None, optional
A location into which the result is stored. If provided, it must have
a shape that the inputs broadcast to. If not provided or None,
a freshly-allocated array is returned. A tuple (possible only as a
keyword argument) must have length equal to the number of outputs.
where : array_like, optional
This condition is broadcast over the input. At locations where the
condition is True, the `out` array will be set to the ufunc result.
Elsewhere, the `out` array will retain its original value.
Note that if an uninitialized `out` array is created via the default
``out=None``, locations within it where the condition is False will
remain uninitialized.
**kwargs
For other keyword-only arguments, see the
:ref:`ufunc docs <ufuncs.kwargs>`.

Returns
-------
y : ndarray or scalar
The truncated value of each element in `x`.
This is a scalar if `x` is a scalar.

See Also
--------
ceil, floor, rint, fix

Notes
-----
.. versionadded:: 1.3.0

Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0., 0., 1., 1., 2.])

typecodes = {'All': '?bhilqpBHILQPefdgFDGSUVOMm', 'AllFloat': 'efdgFDG...

VERSION
1.23.5

FILE
/usr/local/lib/python3.10/dist-packages/numpy/__init__.py

keyboard_arrow_down Robust line model estimation using RANSAC


import matplotlib.pyplot as plt
from scipy import ndimage as ndi
from skimage import feature
import numpy as np
!pip install maskpass -q

!pip install pycountry

Requirement already satisfied: pycountry in /usr/local/lib/python3.10/dist-packages (23.12.11)

im = np.zeros((128, 128))
im[32:-32, 32:-32] = 1

plt.imshow(im, interpolation='nearest', cmap = plt.cm.gray)


plt.show()

im = ndi.rotate(im, 15, mode='constant')


im = ndi.gaussian_filter(im, 4)

# im = im + 0.2 * np.random.random(im.shape)

im += 0.2 * np.random.random(im.shape)

plt.imshow(im, interpolation='nearest', cmap = plt.cm.gray)


plt.show()

edges1 = feature.canny(im)
edges2 = feature.canny(im, sigma = 3)
fig, (ax2, ax3) = plt.subplots(nrows=1, ncols=2, figsize=(8, 3), sharex=True, sharey=True)

ax2.imshow(edges1, cmap = plt.cm.gray)


ax2.axis('off')
ax2.set_title('Canny Filter, $\sigma=1$', fontsize=15)

ax3.imshow(edges2, cmap = plt.cm.gray)


ax3.axis('off')
ax3.set_title('Canny Filter, $\sigma=3$', fontsize=15)

fig.tight_layout()

plt.show()

help(feature.canny)

The ``mode`` parameter determines how the array borders are


handled during Gaussian filtering, where ``cval`` is the value when
mode is equal to 'constant'.
cval : float, optional
Value to fill past edges of input if `mode` is 'constant'.

Returns
-------
output : 2D array (image)
The binary edge map.

See also
--------
skimage.sobel

Notes
-----
The steps of the algorithm are as follows:

* Smooth the image using a Gaussian with ``sigma`` width.

* Apply the horizontal and vertical Sobel operators to get the gradients
within the image. The edge strength is the norm of the gradient.
>>> rng = np.random.default_rng()
>>> # Generate noisy image of a square
>>> im = np.zeros((256, 256))
>>> im[64:-64, 64:-64] = 1
>>> im += 0.2 * rng.random(im.shape)
>>> # First trial with the Canny filter, with the default smoothing
>>> edges1 = feature.canny(im)
>>> # Increase the smoothing for better results
>>> edges2 = feature.canny(im, sigma=3)

fig, (ax1, ax2, ax3) = plt.subplots(nrows=1, ncols=3, figsize=(8, 3), sharex=True, sharey=True)

ax1.imshow(im, cmap = plt.cm.gray)


ax1.axis('off')
ax1.set_title('Noisy Image', fontsize=15)

ax2.imshow(edges1, cmap = plt.cm.gray)


ax2.axis('off')
ax2.set_title('Canny Filter, $\sigma=1$', fontsize=15)

ax3.imshow(edges2, cmap = plt.cm.gray)


ax3.axis('off')
ax3.set_title('Canny Filter, $\sigma=3$', fontsize=15)

fig.tight_layout()

plt.show()

keyboard_arrow_down Robust Fit 3d Points


import numpy as np
from matplotlib import pyplot as plt

from skimage.measure import LineModelND, ransac

rng = np.random.default_rng()

# generate coordinates of line


x = np.arange(-200, 200)
y = 0.2 * x + 20
data = np.column_stack([x, y])

# add gaussian noise to coordinates


noise = rng.normal(size=data.shape)
data += 0.5 * noise
data[::2] += 5 * noise[::2]
data[::4] += 20 * noise[::4]

# add faulty data


faulty = np.array(30 * [(180., -100)])
faulty += 10 * rng.normal(size=faulty.shape)
y g ( y p )
data[:faulty.shape[0]] = faulty

# fit line using all data


model = LineModelND()
model.estimate(data)

True

# robustly fit line only using inlier data with RANSAC algorithm
model_robust, inliers = ransac(data, LineModelND, min_samples=2,
residual_threshold=1, max_trials=1000)
outliers = (inliers == False)

# generate coordinates of estimated models


line_x = np.arange(-250, 250)
line_y = model.predict_y(line_x)
line_y_robust = model_robust.predict_y(line_x)

fig, ax = plt.subplots()
ax.plot(data[inliers, 0], data[inliers, 1], '.b', alpha=0.6,
label='Inlier data')
ax.plot(data[outliers, 0], data[outliers, 1], '.r', alpha=0.6,
label='Outlier data')
ax.plot(line_x, line_y, '-k', label='Line model from all data')
ax.plot(line_x, line_y_robust, '-b', label='Robust line model')
ax.legend(loc='lower left')
plt.show()

output

keyboard_arrow_down Generalize to 3D Points


import numpy as np
from matplotlib import pyplot as plt
from skimage.measure import LineModelND, ransac

# generate coordinates of line


point = np.array([0, 0, 0], dtype='float')
direction = np.array([1, 1, 1], dtype='float') / np.sqrt(3)
xyz = point + 10 * np.arange(-100, 100)[..., np.newaxis] * direction

# add gaussian noise to coordinates


noise = rng.normal(size=xyz.shape)
xyz += 0.5 * noise
xyz[::2] += 20 * noise[::2]
xyz[::4] += 100 * noise[::4]
# robustly fit line only using inlier data with RANSAC algorithm
model_robust, inliers = ransac(xyz, LineModelND, min_samples=2,
residual_threshold=1, max_trials=1000)
outliers = inliers == False

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(xyz[inliers][:, 0], xyz[inliers][:, 1], xyz[inliers][:, 2], c='b',
marker='o', label='Inlier data')
ax.scatter(xyz[outliers][:, 0], xyz[outliers][:, 1], xyz[outliers][:, 2], c='r',
marker='o', label='Outlier data')
ax.legend(loc='lower left')
plt.show()

Start coding or generate with AI.

You might also like