Rafał Skrzydłowski
Rafał Skrzydłowski

Reputation: 11

Get pixels location

I have a question about python and opencv. I would like to change the part of the picture which is black to some other color (no matter what). After changing, I would like to get the pixel values, ​​these 8 points marked with a red circle. How to do it?

https://i.sstatic.net/FGaVk.jpg

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()


Upvotes: 0

Views: 100

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207863

You can do that using OpenCV findContours() and minAreaRect() like this:

#!/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)

The thresholded image looks like this:

enter image description here

And the result image look like this:

enter image description here

The program output is the 4 corner points of the 4 minimum rectangles each one containing one of your lines.

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]]

Upvotes: 1

Related Questions