Mark Adward Mark Adward - 1 year ago 265
Python Question

How realign segments of image in python?

This is the image look like:-
enter image description here

I want to be look like this.:-
enter image description here

Please look, in the second picture button of the image is laved up. I use a software to do this they called this option as segment to 20. I don't have any idea ho to do it in python can anyone please help me ? I am using python 2.7 and i am also new to python so please describe clear with code example. I have tried Opencv vector spacing to do it but all the time give me wrong image.

Answer Source

first use this code for find the objects and save them in /objects folder :

import numpy as np
import cv2

im = cv2.imread('old_image.png') 
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
     [x,y,w,h] = cv2.boundingRect(cnt)
     if h>60:
key = cv2.waitKey(0)


enter image description here

then concatenate the saved objects whit this code :

import numpy as np
import cv2

im0 = cv2.imread('objects/pix0.png',0)
im1 = cv2.imread('objects/pix1.png',0)
im2 = cv2.imread('objects/pix2.png',0)
im3 = cv2.imread('objects/pix3.png',0)
im4 = cv2.imread('objects/pix4.png',0)
im5 = cv2.imread('objects/pix5.png',0)

h0, w0 = im0.shape[:2]
h1, w1 = im1.shape[:2]
h2, w2 = im2.shape[:2]
h3, w3 = im3.shape[:2]
h4, w4 = im4.shape[:2]
h5, w5 = im5.shape[:2]

#add 50 for space between the objects

new = np.zeros((maxh, w0+w1+w2+w3+w4+w5+50),np.uint8)
new[maxh-h0:, :w0] = im0
new[maxh-h1:, w0+10:w0+w1+10] = im1
new[maxh-h2:, w0+w1+20:w0+w1+w2+20] = im2
new[maxh-h3:, w0+w1+w2+30:w0+w1+w2+w3+30] = im3
new[maxh-h4:, w0+w1+w2+w3+40:w0+w1+w2+w3+w4+40] = im4
new[maxh-h5:, w0+w1+w2+w3+w4+50:] = im5
gray = cv2.cvtColor(new, cv2.COLOR_GRAY2BGR)

key = cv2.waitKey(0)

result :

enter image description here

for remove black lines you can comment the line cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),1)

so change it to #cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),1)

result after comment rectangle drawing command !:

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download