Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Articles by Shahid Akhtar Khan
169 articles
How to move a Torch Tensor from CPU to GPU and vice versa?
A torch tensor defined on CPU can be moved to GPU and vice versa. For high-dimensional tensor computation, the GPU utilizes the power of parallel computing to reduce the compute time.High-dimensional tensors such as images are highly computation-intensive and takes too much time if run over the CPU. So, we need to move such tensors to GPU.SyntaxTo move a torch tensor from CPU to GPU, following syntax/es are used −Tensor.to("cuda:0") or Tensor.to(cuda)And, Tensor.cuda()To move a torch tensor from GPU to CPU, the following syntax/es are used −Tensor.to("cpu")And, Tensor.cpu()Let's take a couple of examples to demonstrate how a tensor can be ...
Read MoreHow to normalize a tensor in PyTorch?
A tensor in PyTorch can be normalized using the normalize() function provided in the torch.nn.functional module. This is a non-linear activation function.It performs Lp normalization of a given tensor over a specified dimension.It returns a tensor of normalized value of the elements of original tensor.A 1D tensor can be normalized over dimension 0, whereas a 2D tensor can be normalized over both dimensions 0 and 1, i.e., column-wise or row-wise.An n-dimensional tensor can be normalized over dimensions (0, 1, 2, ..., n-1).Syntaxtorch.nn.functional.normalize(input, p=2.0, dim = 1)ParametersInput – Input tensorp – Power (exponent) value in norm formulationdim – Dimension over which ...
Read MoreHow to join tensors in PyTorch?
We can join two or more tensors using torch.cat(), and torch.stack(). torch.cat() is used to concatenate two or more tensors, whereas torch.stack() is used to stack the tensors. We can join the tensors in different dimensions such as 0 dimension, -1 dimension.Both torch.cat() and torch.stack() are used to join the tensors. So, what is the basic difference between these two methods?torch.cat() concatenates a sequence of tensors along an existing dimension, hence not changing the dimension of the tensors.torch.stack() stacks the tensors along a new dimension, as a result, it increases the dimension.StepsImport the required library. In all the following examples, ...
Read MoreHow to convert a NumPy ndarray to a PyTorch Tensor and vice versa?
A PyTorch tensor is like numpy.ndarray. The difference between these two is that a tensor utilizes the GPUs to accelerate numeric computation. We convert a numpy.ndarray to a PyTorch tensor using the function torch.from_numpy(). And a tensor is converted to numpy.ndarray using the .numpy() method.StepsImport the required libraries. Here, the required libraries are torch and numpy.Create a numpy.ndarray or a PyTorch tensor.Convert the numpy.ndarray to a PyTorch tensor using torch.from_numpy() function or convert the PyTorch tensor to numpy.ndarray using the .numpy() method.Finally, print the converted tensor or numpy.ndarray.Example 1The following Python program converts a numpy.ndarray to a PyTorch tensor.# import ...
Read MoreHow to convert a Torch Tensor to PIL image?
The ToPILImage() transform converts a torch tensor to PIL image. The torchvision.transforms module provides many important transforms that can be used to perform different types of manipulations on the image data. ToPILImage() accepts torch tensors of shape [C, H, W] where C, H, and W are the number of channels, image height, and width of the corresponding PIL images, respectively.StepsWe could use the following steps to convert a torch tensor to a PIL image −Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them.import torch ...
Read MoreHow to detect a rectangle and square in an image using OpenCV Python?
To detect a rectangle and square in an image, we first detect all the contours in the image. Then Loop over all contours. Find the approximate contour for each of the contours. If the number of vertex points in the approximate contour is 4 then we compute the aspect ratio to make a difference between the rectangle and square. If the aspect ratio is between 0.9 and 1.1 we say it is a square else a rectangle See the below pseudocode. for cnt in contours: approx = cv2.approxPolyDP(cnt) if len(approx) == 4: x, y, w, h = ...
Read MoreHow to change the contrast and brightness of an image using OpenCV in Python?
In OpenCV, to change the contrast and brightness of an image we could use cv2.convertScaleAbs(). The syntax we use for this method is as follows − cv2.convertScaleAbs(image, alpha, beta) Where image is the original input image. alpha is the contrast value. To lower the contrast, use 0 < alpha < 1. And for higher contrast use alpha > 1. beta is the brightness value. A good range for brightness value is [-127, 127] We could also apply the cv2.addWeighted() function to change the contrast and brightness of an image. We have discussed it in example 2. Steps ...
Read MoreHow to normalize an image in OpenCV Python?
We use the function cv2.normalize() to normalize an image in OpenCV. This function accepts the parameters- src, dst, alpha, beta, norm_type, dtype and mask. src and dst are input image and output of the same size as input, alpha is lower norm value for range normalization, beta is upper norm value for range normalization, norm_type is normalization type, dtype is data type of output and mask is optional operation mask. Steps To normalize an image, we could follow the steps given below − Import the required library. In all the following examples, the required Python library is OpenCV. ...
Read MoreHow to mask an image in OpenCV Python?
We can apply a mask to an image by computing the cv2.bitwise_and() between the mask and the image. To track a color, we define a mask in HSV color space using cv2.inRange() passing lower and upper limits of color values in HSV.Also Read: Color Identification in Images using Python and OpenCV To track a part of the image we can define a mask using np.zeros() and slicing the entries with white (255) for the region in the input image to examine. Follow the given steps to mask an image − The first step is to import required libraries. The ...
Read MoreHow to compare two images in OpenCV Python?
To compare two images, we use the Mean Square Error (MSE) of the pixel values of the two images. Similar images will have less mean square error value. Using this method, we can compare two images having the same height, width and number of channels. Steps You can use the following steps to compare two images using OpenCV − Import the required library. In all the following Python examples, the required Python library is OpenCV. Make sure you have already installed it. import cv2 Read the input images using cv2.imread() and convert it to grayscale. The height, width and ...
Read More