[英]Extract pixel coordinates and paste on new image python
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)
I do cv2.inRange()
in HSV-space to get the mask for the red region: 我在HSV空间中执行cv2.inRange()
以获取红色区域的蒙版:
Then use the mask-operation(such as cv2.bitwise_and()/np.where()/ slices) to "paste" to another image. 然后使用mask操作(例如cv2.bitwise_and()/ np.where()/ slices)“粘贴”到另一个图像。
To get the coords, you can also use the np.where() like that. 要获取坐标,您还可以像这样使用np.where()。
# 使用 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.