I read an image :
img = cv2.imread("sky.png", 1)
Now, I want to add one pixel in each column for each channel. The way I attempted this is as follows:
img[row_1, :, 0] = np.insert(img[row_1,:,0], column_1, some_value)
img[row_1, :, 1] = np.insert(img[row_1,:,1], column_1, some_value)
img[row_1, :, 2] = np.insert(img[row_1,:,2], column_1, some_value)
Is there a better way of doing this, than to write to each channel separately?
UPDATE: As I have mentioned, that I want to add a new column, that is a 4x4 image, gets transformed to 4x5 image. The value of each pixel is different and the order of columns is also not fixed. For example, first pixel gets inserted into 3 column and second pixel gets inserted into 1 column and so on (using a predetermined set of columns)
Example:
[
[1,2,3,4],
[4,5,6,7],
[8,9,10,11]
]
The above is a 3x4 image (will be a 3 channel image, in reality). I want to convert this to 3x5 image by adding pixels at [0,2] , [1,1], [2,4]
The output then becomes:
[
[1,2, new-pixel-a, 3, 4],
[4,new-pixel-b, 5, 6, 7]
[8, 9, 10, 11, new-pixel-c]
]
So I get a new image, (3, 5)
Looking at the documentation on NumPy's insert method, I would come up with the following solution:
import cv2
import numpy as np
# Read image; output image dimensions
image = cv2.imread('N8e9S.png')
print(image.shape)
# Set up column indices where to add pixels
colIdx = np.array(image.shape[0] * np.random.rand(image.shape[0]), dtype=np.int32)
# Set up pixel values to add
pixels = np.uint8(255 * np.random.rand(image.shape[0], 3))
# Initialize separate image
newImage = np.zeros((image.shape[0], image.shape[1]+1, 3), np.uint8)
# Insert pixels at predefined locations
for i in range(colIdx.shape[0]):
newImage[i, :, :] = np.insert(image[i, :, :], colIdx[i], pixels[i, :], axis=0)
# Output (new) image dimensions
print(newImage.shape)
# Show final image
cv2.imshow('image', image)
cv2.imshow('newImage', newImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
Input image is this one:

The final output looks like this:

Print output to verify new image dimensions:
(241, 300, 3)
(241, 301, 3)
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With