Munazza Ali
Munazza Ali

Reputation: 107

Extract pixel coordinates and paste on new image python

Image

This code is returning pixels coordinates which have red color now i want to extract and paste those pixels on new image. how do i paste pixel coordinates? Please ask if question is not clear.

import cv2
import numpy as np
filename = "oOHc6.png"
img = cv2.imread(filename, 1)
hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
hsv_lower=np.uint8([0, 200, 210])
hsv_upper=np.uint8([180, 250, 250])
mask= cv2.inRange(hsv, hsv_lower, hsv_upper)

#display mask
res = cv2.bitwise_and(img,img,mask = mask)
res_gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)
ys,xs = np.where(res_gray>0)
pts = [(x,y) for x,y in zip(xs,ys)]

empty = np.zeros_like(img)
mask_c = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
imaskc = mask_c>0

empty[imaskc] = img[imaskc]
#empty.save('C:/Python27/cclabel/images/NewImage'+'.png','png')
cv2.imwrite("new.png", empty)

Upvotes: 1

Views: 2912

Answers (1)

Kinght 金
Kinght 金

Reputation: 18331

I do cv2.inRange() in HSV-space to get the mask for the red region:

enter image description here

Then use the mask-operation(such as cv2.bitwise_and()/np.where()/ slices) to "paste" to another image.

enter image description here


To get the coords, you can also use the np.where() like that.

# 使用 cv2.bitwise_and 掩模操作,然后使用 np.where 获取坐标
res = cv2.bitwise_and(img,img,mask = mask)
res_gray = cv2.cvtColor(res, cv2.COLOR_BGR2GRAY)
ys,xs = np.where(res_gray>0)
pts = [(x,y) for x,y in zip(xs,ys)]

To "copy-paste" into another same size image:

## 复制-粘贴到其他空白的地方
empty = np.zeros_like(img)
mask_c = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
imaskc = mask_c>0
empty[imaskc] = img[imaskc]

Upvotes: 1

Related Questions