I am new to Python and I apologize if this is very basic. I am doing image processing but when I read a png image using cv2 and then display the image using plt.imshow() it gives me strange images(Image with extra boundries). I did the following.
import cv2 import numpy as np img1 = cv2.imread('img.png',cv2.IMREAD_GRAYSCALE) plt.figure(figsize=(10,4)) plt.imshow(img1, 'gray') plt.title("ORIGINAL") plt.savefig("original.png") kernel = np.ones((4,4),np.uint8) opening = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel) plt.figure(figsize=(10,4)) plt.imshow(opening, 'gray') plt.title("OPENING OF ORIGINAL") plt.savefig("opening of original.png")
I am attaching the resulting images here.
[the original image]
[After displaying the image through plt.imshow().]
[after doing opening image processing technique]
Advertisement
Answer
Is the extra part you’re talking about a red area?
If I understand correctly, This code can be used to cut the transparent part of the picture
import cv2 import numpy as np import matplotlib.pyplot as plt def cv2_crop(im, box): return im.copy()[box[1]:box[3], box[0]:box[2], :] def get_transparency_location(image): height, width, channel = image.shape assert channel == 4 first_location = None last_location = None first_transparency = [] last_transparency = [] for y, rows in enumerate(image): for x, BGRA in enumerate(rows): alpha = BGRA[3] if alpha != 0: if not first_location or first_location[1] != y: first_location = (x, y) first_transparency.append(first_location) last_location = (x, y) if last_location: last_transparency.append(last_location) top = first_transparency[0] bottom = first_transparency[-1] left = None right = None for first, last in zip(first_transparency, last_transparency): if not left: left = first if not right: right = last if first[0] < left[0]: left = first if last[0] > right[0]: right = last upper_left = (left[0], top[1]) bottom_right = (right[0], bottom[1]) box =upper_left[0], upper_left[1], bottom_right[0], bottom_right[1] result = cv2_crop(image, box) #cv2.imwrite('result.png', result) return result if __name__ == '__main__': #img1 = cv2.imread('img.png',cv2.IMREAD_GRAYSCALE) image = cv2.imread('img.png', cv2.IMREAD_UNCHANGED) img1 = get_transparency_location(image) plt.figure(figsize=(10,4)) plt.imshow(img1, 'gray') plt.title("ORIGINAL") plt.savefig("original.png") kernel = np.ones((4,4),np.uint8) opening = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel) plt.figure(figsize=(10,4)) plt.imshow(opening, 'gray') plt.title("OPENING OF ORIGINAL") plt.savefig("opening of original.png")