获取像素位置

时间:2019-02-05 20:19:13

标签: python opencv

我对python和opencv有疑问。我想将图片的黑色部分更改为其他颜色(无论如何)。更改后,我想获得像素值,这8个点用红色圆圈标记。怎么做?

https://imgur.com/2E1Wwqg

import cv2
import numpy as np

img = cv2.imread("image.jpg");
img[np.where((img == [0,0,0]).all(axis = 2))] = [50,150,166]
cv2.imwrite('output.png', img)
cv2.imshow("shapes", img)
cv2.waitKey(0)
cv2.destroyAllWindows()


1 个答案:

答案 0 :(得分:1)

您可以使用 OpenCV findContours()minAreaRect()来做到这一点:

#!/usr/bin/env python3

import numpy as np
import cv2

# Load image
im = cv2.imread('start.png')

# Convert to grayscale
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)

# Theshold inverse so the black comes out white because findContours() looks for white objects
ret,thresh = cv2.threshold(imgray,16,255,cv2.THRESH_BINARY_INV)
cv2.imwrite('thresh.png',thresh)

# Remove noise specks
thresh = cv2.medianBlur(thresh,5)
cv2.imwrite('thresh-m.png',thresh)

# Find contours, draw on image and save
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im, contours, -1, (0,255,0), 3)

# Show user what we found
i=0
for cnt in contours:
    rect = cv2.minAreaRect(cnt)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(im,[box],0,(255,0,0),2)
    print('Contour:{}\n{}'.format(i,box))
    i = i+1

cv2.imwrite('result.png',im)

阈值图像如下:

enter image description here

结果图像如下:

enter image description here

程序输出是4个最小矩形的4个角点,每个矩形包含一条直线。

Contour:0
[[416 776]
 [410 767]
 [659 607]
 [664 616]]
Contour:1
[[297 780]
 [ 77 599]
 [ 83 592]
 [303 773]]
Contour:2
[[518 695]
 [507 694]
 [519 176]
 [530 177]]
Contour:3
[[226 688]
 [224 174]
 [233 173]
 [235 687]]