0

I want to apply different types of thresholding in a single image but on different parts of it. Is there any way to apply thresholding on specific part of the image rather than in the full image. Below is my code that applies in the full image. How to modify it? import cv2

image = cv2.imread('ANNOTATION01_monitor.PNG')
cv2.imshow('Original',image)
cv2.waitKey()
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale', grayscale)
cv2.waitKey()
ret,thresh1 = cv2.threshold(after_img,30,255,cv2.THRESH_BINARY)
cv2.imshow('Thresholding', thresh1)
cv2.waitKey()

It applies thresholding on the full image. I want to apply this thresholding from (x1,y1) to (x2,y2) this coordinate range.

  • Do you want to get a subimage as a copy (https://stackoverflow.com/a/9085008/18667225) and apply thresholding this subimage? Or can you give an exampe of how the output should look like? – Markus Jan 23 '23 at 09:32
  • @Markus I want to show the full image, applying some thresholding on specific parts of it. Like below image could be an example, where the colored image is B&W in specific part of it. https://i0.wp.com/digital-photography-school.com/wp-content/uploads/2015/06/Half-Color.jpg?fit=717%2C478&ssl=1 – Mahnaz Rafia Islam Jan 23 '23 at 09:49
  • If you want a more general solution that is not restricted to a rectangle region, then create a mask of the size of the input, threshold the image, then user np.where(mask==255, threshold_image, original_image). Be sure all 3 images are the same size and data type. You may have to make the mask and threshold image 3 equal channels (GRAY2BGR). – fmw42 Jan 23 '23 at 22:14

1 Answers1

1

Are you looking for something just like this?

import cv2


x1, y1, x2, y2 = 20, 20, 200, 160

img = cv2.imread('img.png')

roi = img[y1:y2, x1:x2]                                            # get region
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)                       # convert to gray
ret, thresh = cv2.threshold(gray, 64, 255, cv2.THRESH_BINARY)      # compute threshold
bgr = cv2.cvtColor(thresh, cv2.COLOR_GRAY2BGR)                     # convert to bgr
img[y1:y2, x1:x2] = bgr                                            # paste into region

cv2.imshow('output', img)
cv2.waitKey()
cv2.destroyAllWindows()

Example output:

enter image description here

Similar answers:

Markus
  • 5,976
  • 5
  • 6
  • 21