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.
JavaScript
x
17
17
1
import cv2
2
import numpy as np
3
4
img1 = cv2.imread('img.png',cv2.IMREAD_GRAYSCALE)
5
plt.figure(figsize=(10,4))
6
plt.imshow(img1, 'gray')
7
plt.title("ORIGINAL")
8
plt.savefig("original.png")
9
10
11
kernel = np.ones((4,4),np.uint8)
12
opening = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel)
13
plt.figure(figsize=(10,4))
14
plt.imshow(opening, 'gray')
15
plt.title("OPENING OF ORIGINAL")
16
plt.savefig("opening of original.png")
17
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
JavaScript
1
66
66
1
import cv2
2
import numpy as np
3
import matplotlib.pyplot as plt
4
5
def cv2_crop(im, box):
6
return im.copy()[box[1]:box[3], box[0]:box[2], :]
7
8
def get_transparency_location(image):
9
height, width, channel = image.shape
10
assert channel == 4
11
first_location = None
12
last_location = None
13
first_transparency = []
14
last_transparency = []
15
for y, rows in enumerate(image):
16
for x, BGRA in enumerate(rows):
17
alpha = BGRA[3]
18
if alpha != 0:
19
if not first_location or first_location[1] != y:
20
first_location = (x, y)
21
first_transparency.append(first_location)
22
last_location = (x, y)
23
if last_location:
24
last_transparency.append(last_location)
25
26
top = first_transparency[0]
27
bottom = first_transparency[-1]
28
left = None
29
right = None
30
for first, last in zip(first_transparency, last_transparency):
31
if not left:
32
left = first
33
if not right:
34
right = last
35
if first[0] < left[0]:
36
left = first
37
if last[0] > right[0]:
38
right = last
39
40
upper_left = (left[0], top[1])
41
bottom_right = (right[0], bottom[1])
42
box =upper_left[0], upper_left[1], bottom_right[0], bottom_right[1]
43
result = cv2_crop(image, box)
44
#cv2.imwrite('result.png', result)
45
return result
46
47
48
49
if __name__ == '__main__':
50
#img1 = cv2.imread('img.png',cv2.IMREAD_GRAYSCALE)
51
image = cv2.imread('img.png', cv2.IMREAD_UNCHANGED)
52
img1 = get_transparency_location(image)
53
54
plt.figure(figsize=(10,4))
55
plt.imshow(img1, 'gray')
56
plt.title("ORIGINAL")
57
plt.savefig("original.png")
58
59
60
kernel = np.ones((4,4),np.uint8)
61
opening = cv2.morphologyEx(img1, cv2.MORPH_OPEN, kernel)
62
plt.figure(figsize=(10,4))
63
plt.imshow(opening, 'gray')
64
plt.title("OPENING OF ORIGINAL")
65
plt.savefig("opening of original.png")
66